-1

I wrote a program to calculate factorial in c++, but when I compile and run the code, I get some long numbers, for example when I calculate the factorial of 12 I got 4.79002e+08 instead of 479001600.

 #include <iostream>

int main()
{
    int n;
    long double factorial = 1.0;

    std::cout << "Enter a positive integer: ";
    std::cin >> n;

    if (n < 0)
        std::cout << "Error! Factorial of a negative number doesn't exist.";
    else
    {
        for (int i = 1; i <= n; i++)
        {
            factorial *= i;
        }
        std::cout << "Factorial of " << n << " = " << factorial;
    }

    return 0;
}

Note the OS is: ubuntu 20.4

M. Marayef
  • 23
  • 5
  • Use [`fixed`](https://en.cppreference.com/w/cpp/io/manip/fixed) –  Sep 17 '21 at 18:15
  • 3
    Ehr 4.79002e+08 ~= 479001600. Maybe you want to do some output formatting – Pepijn Kramer Sep 17 '21 at 18:15
  • It is the same number in different notation. Try using `std::fixed` and no precision: https://godbolt.org/z/dYhj6hjx7 – rturrado Sep 17 '21 at 18:17
  • 1
    Also remember that factorials get big fast and `long double`s are floating point numbers [and as a result imprecise](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). Sooner or later you will get the wrong answer simply because the system cannot represent it. – user4581301 Sep 17 '21 at 18:19

1 Answers1

0

As said in the comment section long double are floating-point use this instead.

#include <iostream>

int main()
{
    long long int n;
    long long int factorial = 1.0;

    std::cout << "Enter a positive integer: ";
    std::cin >> n;

    if (n < 0)
        std::cout << "Error! Factorial of a negative number doesn't exist.";
    else
    {
        for (int i = 1; i <= n; i++)
        {
            factorial *= i;
        }
        std::cout << "Factorial of " << n << " = " << factorial;
    }

    return 0;
}
Iroh
  • 5
  • 2
  • 5
  • Well, actually, due to the particular nature of factorials, both `double` and `long double` have enough precision to [exactly represent all them](https://godbolt.org/z/zqocdc15x) up to the limit of `long long` and (slightly) above. – Bob__ Sep 19 '21 at 08:55