First off, please seriously name your variables. I know it may just be joking around, but it doesn't help code readability or me or anyone else reading it. This goes for draconic too.
Fonzie has duplicate lines of similar code. Bad, very bad. In particular, the culprit is the input being assigned to age, that is (cin >> age). Also, I do not think there is any significant difference between "first person" and the "next person."
It could be changed like this:
Code: Select all
//...declarations and stuff...
while (age != -1)
{
cout << "Enter a person's age or -1 to quit" << endl;
cin >> age;
if (age != -1)
{
ageTotal += age;
numberOfAges++;
}
}
//...print output...
We are checking the condition age != -1 twice. Bad. One way I can think of solving this is breaking out an infinite loop instead, similar to draconic's approach, like so:
Code: Select all
while (true)
{
cout << "Enter the next person's age or -1 to quit" << endl;
cin >> age;
if (age == -1) break;
ageTotal += age;
numberOfAges++;
}
My approach by the way, instead of using a loop, was building a list of ages recursively (via recursion), then operating on the list to find the sum and number of ages -- I know, a different approach, but it doesn't hurt to hear about it.
[EDIT:] I completely forgot about the case where no ages are entered which may cause division by 0 error - that is a good thing to avoid ;P. Draconic forgot too, hehe.