I did this for the Euler project problem 5, but for some reason I get a floating point exception:
#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
There's a division by zero here because j is initialized to 0.
Since you use i % j
with j
being initialized to zero, you get undefined behavior, according to 5.6 [expr.mul] paragraph 4:
... 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.
Thus the floating point exception.
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.