What I think I need to do next is add a for loop |
What makes you think so?
Why is 'total' a 'double'?
What is the type of 'count'?
What is the value of 'count' before the while-loop?
Input can fail. For example, the user might type text and text is not a number. all following inputs would fail too and the loop would never end. Therefore, it is possible to do more with less:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// your version
cout << "Enter a number: ";
cin >> number;
while (number != -999)
{
total += number;
count++;
cout << "Enter a number: ";
cin >> number;
}
// different version
cout << "Enter a number: ";
while ( cin >> number && number != -999 )
{
total += number;
++count;
cout << "Enter a number: ";
}
|
What does happen there?
The condition of the loop is more complex. It has two substatements and a logical AND (&&).
In order to evaluate that, the left side (
cin >> number
) is evaluated first. The formatted input is carried out, and the statement returns the
cin
.
The cin evaluates to true or false depending on its state.
http://www.cplusplus.com/reference/ios/ios/operator_bool/
If the formatted input did succeed, the left substatement is true.
If the formatted input did fail, the left substatement is false and the number is not valid.
If the left side is false, the && does not even evaluate the right side and simply returns false, and the loop ends.
If the left side is true, then the right side is evaluated, and looping depends on it just like in your version.