Stuck on a C++ problem

Freeeee
Last edited on
Dividing two integers will result in another integer. As soon as one of the operands is a double, the result will be a double too.
So divide by 25.0 instead.

And something unrelated:
count = count + 1 should be shortened to count++
and you should conform to existing standards by using i as a generic counter variable:
for (int i=0;i<25;i++)
I would suggest (for the ability to use this in future classes that have a different size) that you use vectors instead. However, I noticed a couple things that might do it.

You initialized total as 0:
1
2
int total = 0, invalue;
double average = 0.0; 

But you never changed it. So:
average = total / 25;
is the same as:
average = 0/25;

Also, as noted above, you're dividing two integers, and trying to stuff the return into a double.

Change what you have to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main(){
	int total = 0, invalue;
	double average = 0.0;
	ifstream quizData;
	quizData.open("quizdata.txt", ios::in);
	if (quizData.is_open()){
		for (int i = 0; i < 25; i++){
			quizData >> invalue;
			total += invalue;
		}
		average = total / 25.0;
		cout << "The class average was: " << average << endl;

		quizData.close();
	}
	else{cout << "The file could not be opened." << endl;}
	return 0;
} 

and you should be fine.
Topic archived. No new replies allowed.