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!
#include <iostream>
usingnamespace 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