// 1. Create a program that will seek input from the user until
// the user enters a number less than 10.
// After the user enters the numbers print average of all number
//So far I have
#include <iostream>
usingnamespace std;
int main()
{
int num,
sum = 0,
count = 0;
float avg;
cout << "Enter numbers, less than 10 to stop" << endl;
cin >> num;
while (num > 10)
{
sum = sum + num;
count++;
cin >> num;
}
avg = sum;
if(count > 0)
avg = avg/count;
cout << "Average is: " << avg;
return 0;
}
After 10 or less entered I expected to find the average of All numbers, the result is always wrong
Your program works fine, check your math because 421 + 543 + 871 = 1835 and 1835 / 3 = 611.66667. Adding gentleguy's code will not change anything or help.
First you should check your math with a calculator so you know what the program should output.
I also suggest that you change the variables num & sum to float to match avg. Changing them to double would be better because floats can have flaws doing some calculations.
Thank you Andy for your reply.
I know I should absolutely learn and understand this...
I was aiming to include also last number which tells the program it is time to calculate average of all numbers including him... sum/all numbers .
Gentle guys if statemen does the trick but I wasn't able to find out how this works.
well if u want to include the last number then appropriately positioning the if statement will sort that issue out. The code below should work... cheers.
I apologize for my post; in my haste I did not realize that you wanted the last number.
Simple fix though:
1 2
Sum += num;
Count++;
Insert this after the while loop to catch the last number. Then you will get the 461.25 that you want,
In your last if statement you might consider this in case only 1 number is entered:
1 2 3 4 5 6 7 8
if (count > 1)
{
avg = avg / count;
cout << "\n Average is: " << avg;
}
else
cout << "\n Number is: " << avg << " Not enough to average." << endl;