简体   繁体   中英

Why a floating point exception

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

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

Hope this helps!

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.

1000%0是被零除

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM