[英]c++ floating point exception
I did this for the Euler project problem 5, but for some reason I get a floating point exception: 我是针对Euler项目问题5这样做的,但是由于某种原因,我得到了一个浮点异常:
#include <iostream>
using namespace std;
int main ()
{
long num;
bool isnum = false;
long i = 20;
while (isnum == false)
{
for (int j = 0; j <= 20; j++)
{
if (i % j != 0)
{
break;
}
else
{
num = i;
isnum = true;
}
}
i+=20;
}
cout << num << endl;
return 0;
}
What I don't understand is how there can be a floating point exception when I do nothing with my code that would output a non-integer number. 我不明白的是,当我对输出非整数的代码不执行任何操作时,怎么会有浮点异常。
i % j 我%j
There's a division by zero here because j is initialized to 0. 因为j初始化为0,所以这里被零除。
Since you use i % j
with j
being initialized to zero, you get undefined behavior, according to 5.6 [expr.mul] paragraph 4: 根据5.6 [expr.mul]第4段,由于您使用i % j
并将j
初始化为零,因此您将获得未定义的行为:
... If the second operand of / or % is zero the behavior is undefined. ...如果/或%的第二个操作数为零,则行为不确定。 ... ...
This can yield, for example, a floating point exception. 例如,这可能会产生浮点异常。 I can also cause nastier things to happen. 我也会导致更糟的事情发生。
You are doing i % j
with j == 0 at the first iteration of the for
loop. 您正在for
循环的第一次迭代中使用j == 0来执行i % j
。
Thus the floating point exception. 因此浮点异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.