Reputation:
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
Upvotes: 0
Views: 614
Reputation: 320777
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.
Upvotes: 2
Reputation: 229581
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)
Upvotes: 0
Reputation: 1922
You start with counter = 0 and then do a "mod" with counter. This is a division by zero.
Hope this helps!
Upvotes: 6