首页 > 解决方案 > C++ 阶乘函数返回 inf

问题描述

所以我正在编写一个 C++ 程序,该程序旨在获取一个数字的因数,但是当我将一个大数字传递给它时,它以“inf”返回,我试图添加一个 if 语句来检查它是否更大比数据类型的最大大小,是一个长双精度,这不能解决这个问题。有人可以帮忙吗?谢谢。这是我的代码:

long double factoral(long double num)
{
    if (num >= std::numeric_limits<long double>::max() || num < std::numeric_limits<long double>::min())
    {
        return 0;
    }

    if (num > 1)
    {
        return num * factoral(num - 1);
    }

    else
    {
        return 1;
    }
}

int main()
{
    long double res = factoral(1000);

    if (res == 0)
    {
        std::cout << "The factoral of 1000 is either too large or too small";
    }

    else
    {
        std::cout << "The factoral of 1000: " << res;
    }
}

标签: c++

解决方案


inf您的结果在 ( ) 处溢出,return num * factoral(num - 1);因此您只需检查附近的限制,如下所示。

long double factoral(long double num) {

    if (num > 1) {
        long double ret = num * factoral(num - 1);
        if (ret >= std::numeric_limits<long double>::max())
            return 0;
        return ret;
    }

    return 1;
}

我还建议您使用类似(未经测试的代码)的迭代解决方案

long long fac(long long num) {
    long long ret = 1;
    while (num--) ret *= num; //< handle limits here
    return ret;
}

推荐阅读