# Another problem...

• 04-14-2006
StickyGoo
Another problem...
Ok, well I attempted another exercise in the book. It was to 'Write a program that reads in a sequence of positive numbers and prints out the total and average value. The end of the sequence should be signalled by entering -1'.

This is what I came up with:

Code:

```#include <iostream.h> int main() {         int x, y = 0, z = 0;                 while(x != -1)         {                 x = 0;                 cout << "Enter a number: ";                 cin >> x;                 z++;                 y = x + y;         }         y = y + 1;         cout << "The average of those numbers is " << y / z; }```
Only when I enter -1 it messes up and says an error log is being created :(

Thanks if you can help

-Marlon
• 04-14-2006
Daved
The code runs fine for me except for the following:

<iostream.h> is an outdated and non-standard header that doesn't work on my compiler. You use x before it is initialized. You don't actually calculate the average correctly.
• 04-14-2006
jafet
When you enter -1 on the very first run, z is still zero, as you left it. Then you try to do this on the last line:

Code:

`y / z`
;)

By the way please justify this:
Code:

`        y = y + 1;`
• 04-15-2006
Daved
>> When you enter -1 on the very first run, z is still zero, as you left it.
Actually, in the posted code, the first input happens inside the loop where z++ is called, so z will never be zero in that code (unless the uninitialized x happens to end up with a value of -1 in the beginning).
• 04-15-2006
ZuK
Quote:

Originally Posted by jafet
By the way please justify this:
Code:

`        y = y + 1;`

Actually this is correct because the x-value of -1 ( the terminating value ) is still added to y. The code above compensates for that.
Kurt
• 04-15-2006
jafet
Oh, I thought some break mechanism was in the loop. Must've been drunk ;)

I compiled it and entered "-1", and it worked fine.
• 04-16-2006
StickyGoo
I guess it must be this screwy PC... *Sigh*.

... As for all the other questions everyone else seems to have answered them before I could :p

But thank you for the replies :)