Pavlin
Pavlin

Reputation: 5528

c++ floating point exception

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.

Upvotes: 0

Views: 597

Answers (3)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153830

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.

Upvotes: 3

Y__
Y__

Reputation: 1777

You are doing i % j with j == 0 at the first iteration of the for loop.

Thus the floating point exception.

Upvotes: 1

LoSciamano
LoSciamano

Reputation: 1119

i % j

There's a division by zero here because j is initialized to 0.

Upvotes: 8

Related Questions