0

I've tried a debugger and Catch and throw, though I confess I'm not comfortable with either. But I'm not able to find the cause of Floating Point Exception in my program. The weird thing is it runs perfect for numbers <= 35. Beyond that, it raises the exception. Where's the problem?

int fibo(int n)
{   if(n==0 || n==1)
        return 1;
    int p=1;
    while(n>1)
        p*=(n--);
    return p;
}

int main()
{   int T;
    int N, M;
    cin>>T;
    for(int i=0; i<T; i++)
    {
        cin>>N>>M;
        int cnt=1;
        int ones=N, twos=0;
        if(ones==1 && M==1)
        {   cout<<"CORRECT"<<endl;
            continue;
        }
        else if(ones==1 && M!=1)
        {   cout<<"INCORRECT"<<endl;
            continue;
        }

        while(ones>=2)
        {   
            ones-=2;
            twos++;
            cnt+= fibo(ones+twos)/( fibo(ones) * fibo(twos) );
        }
        cout<<cnt<<endl;
        int tmp=0;
        while(cnt>0)
        {   if(cnt%2 == 1)
                tmp++;
            cnt/=2;
        }
        if(  tmp==M  )
            cout<<"CORRECT"<<endl;
        else
            cout<<"INCORRECT"<<endl;
    }

    system("pause");
    return 0;
}

Thanks a lot.

Chocolava
  • 1,466
  • 2
  • 16
  • 20
  • 2
    I don't see any floats or doubles... How can there be a problem with floating point exception? – swtdrgn Feb 02 '13 at 06:52
  • I'm totally baffled. Happens for every number 36 and above. I tried it on Visual Studio first, then Linux, same everywhere. – Chocolava Feb 02 '13 at 06:54
  • 1
    It would help to see on which line it happens or better yet the minimal piece of code reproducing the problem (without user input or loops, just the factorial function, that division and constants). You might be getting into a division by 0 problem or division overflow (INT_MIN/-1), but it's hard to tell definitely. – Alexey Frunze Feb 02 '13 at 06:58
  • 1
    Disable code optimization and step through the program. See where the exception happens and with what values. – Alexey Frunze Feb 02 '13 at 07:01

1 Answers1

1

A "floating-point exception" is not a C++ exception. try and catch won't help you. It's unfortunate terminology but it comes from the OS and is more like a "crash".

Even more baffling, you can see it on some platforms when trying to perform integer division by zero. I haven't unravelled your code, but add in plenty of debug output and track the values of your variables, and find the place where you're dividing by zero because, well, you're doing it somewhere. :)

The only place I can see that's a candidate is:

cnt+= fibo(ones+twos)/( fibo(ones) * fibo(twos) )
//                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055