You don't need to use the entire std namespace, when it looks like just cin and cout will do fine.
using std::cin; using std::cout;
main() should return an int, and that int should be 0:
1 2 3 4 5
|
int main()
{
//code
return 0;
}
|
Why do you initialize some variables but not all? Initialize them all to 0:
1 2 3 4
|
int num=0;
int total=0;
int count=0;
int average=0;
|
This line from the OP:
|
while (total + num > 250){
|
Tests the current total, not the average, and loops only if the total is GREATER than 250.
This line from the first response:
|
while ((total + num) < 250) {
|
Still only tests the current total, not the average, though it corrects the > to <.
To ensure that your while loop executes at least once, make it a do...while loop, make it test the average, and make it loop if the average is less than 250:
1 2 3 4 5 6 7 8
|
do {
cout << "Enter number: ";
cin >> num;
total+=num;
count++;
average = total/count;
} while(average<250);
|
You also have an extra "<< count <<" in your final cout statement:
|
cout << count << " numbers were read in. " << count << "The average is: " <<...
|
should be changed to:
|
cout << count << " numbers were read in. The average is: " << average...
|
Also, did you want your 250 cap to be a hard cap (meaning the final average MUST be less than 250) or a soft cap (meaning the final average can be the amount that meets or breaks 250)? If you want a hard cap, you would have to add a test that would prevent values from changing if the new average goes over 250.
|
if(average>250) { total-=num; count--; average = total/count; break; }
|
This line undoes the last set of changes and exits the loop with the previous values for total, count, and average. This line could be added to the end of the while loop to implement a hard cap, or you can run the test earlier:
1 2 3 4 5 6 7 8 9
|
do {
cout << "Enter number: ";
cin >> num;
if( (total+num / count+1) > 250 ) { break; }
total+=num;
count++;
average = total/count;
} while(average<250);
|
This will pretest the math and break the loop before any values are changed. Optionally, you could make this code much cleaner by just using a function that takes and returns values and encapsulates the arithmetic and tests within it:
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
|
#include <iostream>
using std::cin; using std::cout;
bool Calculate(int&,int&,int&);
int main() {
int total=0, count=0, average=0;
for(bool done=false;!done;) {
done = Calculate(total,count,average);
}
cout << count << " numbers were read in. The average is: " << average << ".n";
return 0;
}
bool Calculate(int& total, int& count, int& average) {
int num=0, tempTotal=total, tempCount=count, tempAverage=average;
cout << "Enter number: ";
cin >> num;
tempTotal+=num;
tempCount++;
tempAverage=tempTotal/tempCount;
if(tempAverage>250) { return true; }
else {
total=tempTotal;
count=tempCount;
average=tempAverage;
return false;
}
}
|