Search code examples
recursiondoubleoverflowfactorial

C++ "double" variable overflows too early


I have written a simple code to try if compiler on my new computer works properly. There is no problem to compile/build the project. The programme should calculate factorial by recursion and it works fine but only under 13!(It is only about x*10^9, double should have range up to x*10^308). If I try higher numbers, it gives me negative results etc. I can't find out what causes the problem. On my old computer(32 bit win xp) worked the same code properly up to 170! (but i am not sure if it was exactly the same because main part of my data have been lost). Sholud I reinstall compiler or is there something wrong with settings? Or my code is incorrect?

My current pc has 64-bit win7 and AMD processor. I am using now MS Visual Studio 2012 update 2.

I am newbie to c++ and also sorry for my bad English.

Here is my code:

    #include <iostream>

    using namespace std;

    int factorial(int x){
        if (x==2){ return 2;}
        return x*factorial(x-1);
    }

    int main()
    {
        double x,v;
        cout<<"insert number: ";
        cin>>x;
        v=factorial(x);
        cout<<"\n"<<v<<"\n";
        system("pause");
        return 0;
    }

Solution

  • Shouldn't it be:

    double factorial(double x)
    

    Otherwise it will convert your number to an int and overflow.

    EDIT: Do you have warnings disabled? I think the factorial(x) call should emit a warning about losing precision...