# Thread: Possible off by 1 error

1. ## Possible off by 1 error

So i'm assigned to enter a list of real numbers and to enter -1 if I want to end the list. After that I must find the average of the numbers entered. Here is my code:

Code:
```main()
{
float num, sum = 0.0, i = 0.0;

printf("Enter a list of real numbers. \n");
printf("Enter -1 to terminate the list.\n");

while (num != -1)
{
scanf("%f", &num);
sum += num;
++i;
}

printf("The average is %.2f\n", sum / i);

}```
Code:
```Enter a list of real numbers.
Enter -1 to terminate the list.
1
2
3
-1
The average is 1.25```
As you can see this is obviously not the average of 1 + 2 + 3 = 6 / 3 = 2.00 not 1.25.

I tried ++i as well as setting i = 1.0 instead of 0.0 but still no logical equivalence.

Is there an explanation as to why? 2. One problem is that you did not initialise num, so the first comparison of num != -1 compares garbage to -1. The problem that you are observing is that when -1 is entered, you add -1 to sum instead of ignoring it.

A simple way to fix this is to repeat the scanf call: once before the loop, and once at the end of the loop body. 3. main() should be int main().
Now, as for the issue, ponder what happens on the last loop when you enter -1. Remember to keep track of what values sum and i are! You will soon realize what's wrong. Originally Posted by laserlight A simple way to fix this is to repeat the scanf call: once before the loop, and once at the end of the loop body.
I would say an easy solution is to initialize sum to something non -1, or use a do ... while loop. 4. Originally Posted by Elysia
I would say an easy solution is to initialize sum to something non -1, or use a do ... while loop.
sum has already been correctly initialised to 0.0. An alternative solution to what I suggested would be to initialise num to 0 and then just shift the scanf to the end, but I think that that might be more difficult to see as correct at a glance (in both cases the initial value of i has to be modified). A do while loop can work, but again avoiding adding -1 is not so easy without uglier duplication. 5. Ah sorry, I meant num, not sum. 6. On second thought, with my suggestion, the initial value of i should not be modified, i.e., it would be correct to keep it initialised to 0. 7. Just use for loop!

Code:
```int n;
float num,sum;
sum = 0;
for(n = 0; scanf("%f",&num) == 1 && num != -1.0; n++) {
sum += num;
}``` 8. figured it out...thanks guys! Popular pages Recent additions 