i have a program where i need to know the average of a string of numbers. the user inputs their numbers and enters -1 to submit the numbers, but when it calculates the average it also uses the -1, how do i make it disregard the -1?
int main ()
{
double value, high= 0, low= 0, average, count=0,total=0;
char again= 'y';
cout << "Enter a series of positive numbers (-1 when done) : " << endl;
cin >> value;
while (value != -1)
{
if (value > high)
high=value;
if (count !=0)
average=(total) / count;
if (count > low)
low=count;
total=total+value;
count++;
cin>> value;
}
cout << " The high value is " << high << endl;
cout << " The low value is " << low << endl;
cout << " The average is " << setprecision (2) << fixed << average << endl;
Well no, i need to enter a -1 to submit the users input. but when it calculates the average it is also adding the -1, i want it to only recognize -1 as the submit, not part of calculating the average
No, for the series of numbers to be submitted into the loop and to execute it you need to enter -1
Like if i wanted: 2, 4, 5,98 to be input i would need to put -1 at the end of that string of numbers to enter it. so when i want to have the average of all those numbers but without taking the -1 into account.
I'm perfectly aware of what a sentinel value does. My question is still: If the body of the loop doesn't execute when value is -1, how does it end up affecting the average?
What output would you expect for the input seqence 2 -1? What output do you get if you actually use that sequence when you run it?
Well, the OP was asking the wrong question. I could look at the code and see that obviously average was not being affected by the sentinel value, so I didn't feel a need to test the code. When I did take a closer look...
First average is never initialized. When you enter your first value as -1 you are treated to some trash output. (You're treated to the same display when you only enter 1 value and then the sentinel because of a bug in the body of the loop.)
Second, in order for the average to be calculated correctly, the count and total variables must be updated before the average. This doesn't happen on either account.
Third, the low variable was being compared to and assigned the value of count instead of value.
I would suggest initializing average to 0 and changing the loop to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
while (value != -1)
{
++count ;
total+= value ;
average = total/count ;
if (value > high)
high=value;
if (value < low)
low=value;
cin>> value;
}
I agree with GRex2595. Fill a buffer with all the values until less than zero (negative). Then do all the calculation from the values in the buffer. Or do the while loop test on >= 0 instead of test for -1. What if it's -2???
Cire, thanks a lot your post was a huge help!
i can get high and average to do what i want, however the low is now always displayed as the same as High