-
Loop structuring problem
I am having a problem with my loop structure code:
Code:
#include <iostream>
using namespace std;
void main( )
{
cout << "Value 0 will end process!" << endl;
double Average = 0.00;
int Sum = 0;
int Counter = 0;
int temp;
do
{
cout << "Enter Temperature:";
cin >> temp;
Sum += temp;
Counter++;
}
while(temp != 0);
Average = Sum / Counter;
cout << "Average Temperature = " << Average << endl;
}
/* Captured output
Enter Temperature:78
Enter Temperature:90
Enter Temperature:85
Enter Temperature:80
Enter Temperature:87
Enter Temperature:83
Enter Temperature:75
Enter Temperature:90
Enter Temperature:86
Enter Temperature:70
Enter Temperature:0
Average Temperature = 74
Press any key to continue . . .
*/
I have a trip value of 0 set to the code so it will end the loop. What I am trying to figure out is how to dismiss the 0 from the calculation of the average in the loop so it will only calculate however many entries there are until you end the loop with a 0. Anyone got an idea?
-
You could put into the body of the loop:
Code:
if(temp == 0) break;
However, it's not good to use "0" as a terminating condition though, because the temperature of '0 degree' is a valid. You want to think of different terminating condition.
BTW, Average is not calculated correctly. Both Sum and Counter are type int. The value of Average will be the truncated result of Sum/Counter.