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

程序出现Runtime Error:无返回结果且无法终止运行问题排查

程序卡死的原因与修复方法

你的程序运行时无响应、进程无法终止,问题出在Recursion方法里的无限递归,还有两处逻辑错误:

  • 缺少递归终止条件:当输入的数是个位数时,方法仍会调用自身,导致无限循环,最终引发栈溢出(StackOverflowException),程序卡死。
  • 字符转数字错误:Convert.ToInt32(str[i])会把字符转为对应的ASCII码(比如字符'1'会转成49),而非实际的数字值。
  • 累加变量未重置:sum在循环中没有每次清零,会导致后续计算结果错误。

修复后的完整代码

class DigitalRoots
{
    static void Main(string[] args)
    {
        Console.Write("Enter a non-negative integer: ");
        int numbers = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(DigitalRoot(numbers));
        Console.WriteLine(Recursion(numbers));
    }

    static int DigitalRoot(int num)
    {
        if (num < 10)
        {
            return num;
        }
        else
        {
            int sum = 0;

            while (num > 0)
            {
                sum += num % 10;
                num = num / 10; 
            }

            return DigitalRoot(sum);
        }
    }

    static int Recursion(int num)
    {
        // 新增:递归终止条件,个位数直接返回
        if (num < 10)
        {
            return num;
        }
        
        int sum = 0;
        string str = Convert.ToString(num);

        while(str.Length > 1)
        {
            sum = 0; // 每次循环重置sum,避免累加旧值
            for (int i = 0; i < str.Length; i++){
                // 字符转数字:减去'0'的ASCII值,得到实际数字
                sum += str[i] - '0';
            }
            str = Convert.ToString(sum);
        } 

        int result = Convert.ToInt32(str);
        return Recursion(result);
    }
}

更高效的数字根计算方式

数字根可以用数学公式直接计算,无需递归或循环,效率更高:

static int DigitalRootFast(int num)
{
    return num == 0 ? 0 : num % 9 == 0 ? 9 : num % 9;
}

内容的提问来源于stack exchange,提问作者Caleb Olawale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:38:31