Help! I have to write a program that reads and array and computes the average. My problem is that it's not returning the correct value. It always comes back with an average of 1. I've checked both the values of length and total before and after the for loop in mean_average and they're fine, but the return value is getting lost somewhere and I just can't figure out why. Any help would be greatly appreciated!
void getList(int[], int&);
void putList(constint[], int);
float mean_average(constint[], int);
int main()
{
int nums[MAXNUMS];
int length;
getList(nums,length);
putList(nums,length);
mean_average(nums,length);
cout<<"The average value of the array is "<<setiosflags(ios::fixed)<<setprecision(3)<<mean_average<<"."<<endl;
return 0;
}
void getList(int nums[],int& length)
{
int i;
cout<<"Please enter the numbers of array values.\n";
cin>>length;
for(i=0;i<length;i++){
cout<<"Please enter the next array value."<<endl;
cin>>nums[i];
}
}
void putList(constint nums[],int length)
{
cout<<"List of array elements."<<endl;
for(int i=0;i<length;i++){
cout<<i<<" "<<nums[i]<<endl;
}
}
float mean_average(constint nums[], int length)
{
int total;
for(int i=0;i<length;i++){
total=total+nums[i];
}
return total/length;
}
line 49 - total and length are both integers, so you'll get an integer division result.
line 46 - total isn't initialized before you first use it here. I'd initialize a running total counter to 0 (or 0.0 if you make total a float instead of int) so there isn't a random garbage value in it.