You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻找各位数字阶乘和等于自身的三位数:代码无输出问题排查

代码问题排查与修复

问题根源

  • 阶乘函数未处理0的情况:数学定义中0! = 1,但当前fact函数仅设置了y=1的终止条件,当输入y=0时,会触发递归调用fact(-1),进而引发无限递归(最终导致栈溢出),使得各位含0的数字计算出错误的阶乘和,无法匹配目标数。
  • 递归未添加负数防护逻辑,虽本场景不会传入负数,但存在潜在程序崩溃风险。

修复方案

修改fact函数,补充0!的处理分支,同时增加负数输入的防护:

#include <iostream>
using namespace std;

int fact(int y);
int test(int x);

int main()
{
    for (size_t i = 100; i < 1000; i++)
    {
        int sum = 0;
        int x = i;
        while (x > 0)
        {
            sum += test(x);
            x /= 10;
        }

        if (sum == i)
        {
            cout << i << endl;
        }
    }

    return 0;
}

int fact(int y)
{
    // 处理0的阶乘,同时防护负数输入
    if (y <= 0)
    {
        return 1;
    }
    else if (y == 1)
    {
        return 1;
    }
    else
        return y * fact(y - 1);
}

int test(int x)
{
    int r = x % 10;
    return fact(r);
}

验证结果

修复后运行代码,会输出符合条件的三位数:145(计算逻辑:1! + 4! + 5! = 1 + 24 + 120 = 145)。

内容的提问来源于stack exchange,提问作者Andy James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:03:32