Reputation: 17
I am supposed to allow the user to enter non-negative numbers, and once a negative number is entered, the function should display the average of the proceeding non-negative numbers.
I am using XCode to do C++ work.
int Question6(){
double nums;
double totalnums = 0;
int count = 0;
cout << "Please enter the numbers that you like to be average that are non-negative:";
cin >> nums;
while (nums > 0){
cout << "Please enter the numbers that you like to be average that are non-negative:";
cin >> nums;
totalnums += nums;
count += 1;
if (nums < 0){
cout << "You have enterd a negative number so your average is:" << (totalnums/ count) << endl;
}
}
return 0;
}
I have gotten the build to be successful but it always gives me a average with the negative number included. Is there a way to stop this from happening?
Upvotes: 0
Views: 120
Reputation: 16156
A cleaner solution - with error checking - is to loop while you have valid input, and then decide what to do based on the sign of the input:
while (std::cin >> number)
{
if (number >= 0)
{
// update values needed for average calculation
}
else
{
// calculate average, display
break; // exit the while loop
}
}
// Optionally: Check if loop exited due to read error or negative number
if (std::cin)
{
// read a negative value
}
else
{
// IO error (such as eof, no more numbers)
}
Upvotes: 1
Reputation: 2416
The problem is here:
while (nums > 0)
{
cout << "Please enter the numbers that you like to be average that are non-negative:";
cin >> nums;
totalnums += nums;
count += 1;
if (nums < 0)
{
cout << "You have enterd a negative number so your average is:" << (totalnums/ count) << endl;
}
}
The problem is the if
instruction in the while
loop. If you enter a negative number, it gets added to your totalnums+=nums
instruction, because it's the next instruction after cin
. After that, the while
condition becomes false
and the program exits the loop.
To fix your bug, check if nums<0
before you enter the while
loop.
Upvotes: 3