什么数据类型可以存储 100 的阶乘

Kri*_*Oza 7 c++ type-conversion factorial

为什么下面的程序将 100 作为输入的阶乘打印为 0。如果 getFact 函数返回类型为 ,则可以计算相同的阶乘long double,但为了获得数字总和,我无法在 long double 上应用mod (%)运算符。

注意:unsigned long long和的大小long double在我的机器上相同。请建议输入为 100 什么类型的数据会给出正确的输出。

#include <iostream>
#include <stdlib.h>

unsigned long long int getFactorial(int);
unsigned long long int getSum(unsigned long long int);

int main()
{
    unsigned long long int fact = 1;
    unsigned long long int digsum  = 0;
    std::cout << "Enter a number to find fact := ";
    int num;
    std::cin >> num;
    fact = getFactorial(num);
    std::cout << num <<"'s factorial is = " << fact << std::endl;
    digsum = getSum(fact);
    std::cout << sizeof(unsigned long long int) << std::endl;
    std::cout << sizeof(long double) << std:: endl;
    std::cout << "Sum of the digits in the number" << num << "! is :=" <<  digsum << std::endl;
    return 0;
}

unsigned long long int getFactorial(int num)
{

    if(num == 1)
        return 1;
    else
        return (num * getFactorial(num - 1));
}


unsigned long long int getSum(unsigned long long int fact)
{
    if(fact == 0)
        return 0;
    else
    {
        int temp = 0;
        temp = fact % 10;
        return (temp + getSum(fact/10));
    }
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*ain 4

如果你想要一个近似值,你可以使用 double。(注意整数算术与双精度不同)。您可以使用log计算或乘法来估计100!

但是因为你想要数字之和,你需要精确的结果,你需要一些大的整数库。你可以谷歌搜索大整数。

或者,您可以将大数字存储为字符串,并按照我们在学校学到的方式使用笔和纸执行计算(乘积)。