average problem

Sep 2, 2010 at 12:54pm
I'm trying to do this exercise from the book accelerated c++ by Koeing & Moo (chapter 3), which basically it should calculate the average of the grades midterm, final & homework.... The problem is that the answer i'm getting is only the sum of the grades thus i think that i'm missing something regarding the count... any ideas please ??
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
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>


using namespace std;

int main ()
{	cout << "Please enter your Midterm and Final grades : ";

double midterm, final;
cin >>  midterm >> final;

	cout << "Please enter your Homework grades, followed by end of file: " << endl;

int count = 0;
double sum = 0;
double x;

while ( cin >> x ) 
	{ ++count;
	sum += x; } 

streamsize prec = cout.precision(3);
cout << "Your final grade is " << (midterm + final + sum) / count << endl; 
cout.precision(prec); 

return 0;
}
Sep 2, 2010 at 2:04pm
Seem ok to me. Try below with extra pair of parenthesis.

cout << "Your final grade is " << ( (midterm + final + sum) / count ) << endl;


Sep 2, 2010 at 2:09pm
Rename sum to homework_sum and count to homework_count and you'll see the mistake (probably).
Sep 2, 2010 at 2:42pm
tried both of your suggestions, but still only the sum as output....
Sep 2, 2010 at 2:45pm
It seems to work for me on Linux but you should avoid doing this: using namespace std; It pollutes the global namespace and introduces a lot of symbols that you don't expect to be defined. Two of which are sum and count. So to avoid hard to find conflicts it is highly recommended to stop doing using namespace std;.
Sep 2, 2010 at 2:46pm
You may change count datatype to double, eventhough logical wrong :), expert will tell you.
Sep 2, 2010 at 2:50pm
Actually, I am not convinced by your math. You only count the number of homework assignments and do not take the first two results into consideration in the count. So I think your count should begin at 2 to account for the first two grades input.
 
int count = 2;
Sep 2, 2010 at 2:54pm
i use linux aswell and the code didn't work, but as soon as i did the int count = 2; it worked....... thanks again for your advice....
Sep 2, 2010 at 3:06pm
I doubt that it works as intended. The total grade is made up 1/3 each by midterm, final and homework.
The total homework grade consists of the average grade of the individual homework grades.
Topic archived. No new replies allowed.