+ 1
Why this C++ code is giving wrong output?
I wrote a program which takes user input ten times and than outputs their average in C++. But my program is giving 0 as output. I can't figure out where is the problem. Please Help. This is the code: #include <iostream> using namespace std; void calc(int arg){ int i; cin>>i; arg += i; } int main(){ int sum = 0; for(int i=1; i<=10;i++){ calc(sum); } int o = sum/10; cout<<o; return 0; }
2 Respostas
+ 2
Change the signature for function calc to accept its argument by reference rather than by value.
void calc( int& arg )
Also it is recommended to use a floating point type for variable <o> because integer division ignores decimal points in the division result.
double o = (double)sum / 10;
+ 2
Because u are calling calc by value not buy it's reference and you are storing result of a division into an int which is not good practice.
try this program here I am calling calc by its reference so changes in arg directly reflect to sum. and using flot o instead of int o
#include <iostream>
using namespace std;
void calc(int *arg){
int i;
cin>>i;
*arg += i;
}
int main(){
int sum = 0;
for(int i=1; i<=10;i++){
calc(&sum);
}
float o = sum/10;
cout<<o;
return 0;
}