tags:

views:

104

answers:

4

Hi,

Just trying out some C on some of the project euler questions.

My question is why am I getting a floating point exception at run time on the following code?

#include <stdio.h>
main()
{
int sum;
int counter;

sum = 0;
counter = 0;

for (counter = 0; counter <= 1000; counter++)
{
    if (1000 % counter == 0) 
    {
        sum = sum + counter;
    }
}

printf("Hello World");
printf("The answer should be %d", sum);
}

Thanks,

Mike

+7  A: 

You start with counter = 0 and then do a "mod" with counter. This is a division by zero.

Hope this helps!

avpx
Bingo! Mike, please close your Q.
Hamish Grubijan
Thanks! Good old brain fart.
Mike
A: 

What happens when counter is 0? You try to compute 1000 % 0. You can't compute anything modulo 0, so you get an error.

Your if statement should read:

if (counter % 1000 == 0)
Claudiu
The only values for which counter % 1000 is 0 are 0 and 1000, so I'm not sure that the second part of your answer is correct? In fact, since the code appears to be finding and summing factors of 1000, I think the correction OP needs is "for ( counter = 1;"
Tony van der Peet
+1  A: 

1000 % 0 is a division by zero

Andy White
+2  A: 

You are dividing 1000 by zero on the first iteration (calculating a reminder of something divided by 0). Why it crashed with a floating-point exception... I don't know. Maybe the compiler translated it into a floating-point operation. Maybe just a quirk of the implementation.

AndreyT
I think the "floating point exception" message is operating system related. When the processor encounters a division by zero it executes a trap to the "divide by zero" handler of the system. Interestingly (and curiously), this handler on linux systems displays the "floating point exception" message.
3lectrologos