Returning values to main

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
void getList(int[], int&);
void putList(const int[], int);
float mean_average(const int[], 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(const int nums[],int length)
{
	cout<<"List of array elements."<<endl;
	
	for(int i=0;i<length;i++){
	cout<<i<<" "<<nums[i]<<endl;
	}
}

float mean_average(const int 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.
I tried that, but no change. I even tried casting length to a float, but it still only returns a 1.
How are you doing the cast? This works for me.

return static_cast<float>(total)/length;
That's how I was doing it, but to no avail...
line 14 - put what you have in line 13 (the function call with parameters) in place of just mean_average


this by itself in line 13 calls the function, but doesn't do anything with the return value.
mean_average(nums,length);

mean_average by itself (without parenthesis and parameters) doesn't call the function.
Last edited on
That's it! That's what I was missing. Oh my goodness, thank you! This was driving me MAD!
You're welcome - glad it's working for you now :)
Topic archived. No new replies allowed.