Trouble with average in loops

Hey everyone, so i am supposed to write a loop that calculates the average of the numbers inputed, once the loop has been closed. Ive tried everything i can think of and the avg still comes out to 0, thanks!
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
  #include <iostream>
using namespace std;
int main()

{
	int count = 0;
	int total = 0;
	float avg = 0;
	int num;
	cout << endl << "Enter numbers, 999 to quit" << endl;
	cin >> num;
	while (num != 999)
	{
		cout << "Number entered is" << num << endl;
		count = count + 1;
		cout << "The total numbers entered are" << count << endl;
		count = count;
		cout << "The total of the numbers is" << total+num << endl;
		total = total + num;
		cout << "Enter numbers, 999 to quit" << endl;
		cin >> num;

	}
	//average
	cout << "The average of the numbers is " << avg<< endl;
	avg = total / num;

	return 0;
}
avg = total / num;

Should be :
avg = total / count;
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
#include <iostream>
using namespace std;
int main()

{
	int count = 0;
	int total = 0;
	float avg = 0;
	int num=0; // always set values

// not needed
//	cout << endl << "Enter number, 999 to quit" << endl;
//	cin >> num;

	while (num != 999)
	{
	// Personal preference to do all the math together if possible.
	count = count + 1;
	total = total + num;

		cout << "Number entered is " << num << endl;
		cout << "The total numbers entered are " << count-1 << endl;
	// count = count; This does nothing
		cout << "The total of the numbers is " << total << endl; 

		cout << "Enter numbers, 999 to quit" << endl;
		cin >> num;

	}
	//average
	avg = total / (count-1);  // This was after your cout, reason your output below was 0
	cout << "The average of the numbers is " << avg << endl;

	return 0;
}
while (num != 999)
What if the user wants to input 999 as a number?
Consider this instead: while( cin >> num ). As long as the user enters a number, the loop will continue. If the user enters in a character, for example, the loop will terminate.

avg = total / num;
Integer division. Cast one to a float to get a floating point answer.
I did while(num!=999) because those were the instructions given by my instrucutur :P,
Also thank you everyone for the responses, i took SamuelAdams tips and improved my code
Last edited on
Topic archived. No new replies allowed.