[英]Why a floating point exception
Just trying out some C on some of the project euler questions. 只需在一些项目欧拉问题上尝试一些C语言即可。
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. 您从counter = 0开始,然后对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). 您将在第一次迭代中用1000除以零(计算出除以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? counter
为0会怎样? You try to compute 1000 % 0
. 您尝试计算
1000 % 0
。 You can't compute anything modulo 0, so you get an error. 您无法计算任何模0模,因此会出现错误。
Your if statement should read: 您的if语句应为:
if (counter % 1000 == 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.