c++ - 当阶乘对于 C++ 中的 int 来说太大时如何处理?

标签 c++ error-handling

我有这个用于查找阶乘的递归函数,但我不知道如何修改它以在阶乘对于 int 来说太大时抛出错误。

如果我的函数是迭代的,我可以只放入一个 if 语句,每次检查阶乘是否为 0 或更小,从而找到发生溢出的位置,但这对于递归定义似乎不可行。

int factorial(int x)
{
    if (x < 0) error("Can't take factorial of a negative number.");
    else if (x == 0) return 1;
    else return x * factorial(x - 1);
}

例如,如果我用 50 调用该函数,它将返回 0。在这种情况下我想抛出一条错误消息。谁能帮我解决这个问题?

最佳答案

阶乘函数是一个静态函数,在给定相同输入的情况下,其输出始终相同。因此,我们可以提前知道给定的输入是否会溢出。

int32_t factorial(int32_t val) {
    if(val > 12)
        throw std::runtime_error("Input too large for Factorial function (val must be less than 13)");
    if(val < 0)
        throw std::runtime_error("Input must be non-negative");
    if(val == 0)
        return 1;
    return factorial(val-1) * val;
}

int64_t factorial(int64_t val) {
    if(val > 20)
        throw std::runtime_error("Input too large for Factorial function (val must be less than 21)");
    if(val < 0)
        throw std::runtime_error("Input must be non-negative");
    if(val == 0)
        return 1;
    return factorial(val-1) * val;
}

如果您想改为动态检测整数溢出,则需要查看 rigorous methods for detecting possible overflow .

关于c++ - 当阶乘对于 C++ 中的 int 来说太大时如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344702/

相关文章:

json - 如何在laravel中为api返回json格式而不是html

c++ - 你如何让系统在 C++ 中工作?

c++ - 预编译 header IntelliSense 错误

php - 在网站管理员工具中,googlebot从服务器获取抓取错误500

ios - 在 try catch 中分解 catch 子句

error-handling - 使用robotframework在登录脚本中添加电子邮件和密码

java - 获取不兼容的类型和数组所需的错误

c++ - 如何在C++中调用execute命令行

C++:从基类型指针确定派生类型

c++ - 为什么 gettimeofday() 间隔偶尔为负数?