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

阶乘函数未返回预期值,NUnit测试用例验证失败求助

问题分析与修复方案

嘿,这问题一眼就能看出来啦!你得到的3125其实是5^5(5的5次方),而不是我们要的5的阶乘5×4×3×2×1=120——这说明你的Factorial方法逻辑写错了,大概率是把阶乘的递减相乘逻辑写成了重复乘以输入值。

先梳理下你给出的测试用例和问题背景:

你的测试用例

using System;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class SolutionTests {
    [Test]
    public void Test1() {
        var solution = new Solution();
        Assert.AreEqual(solution.Factorial(5), 120);
    }
}

问题根源

从结果反推,你当前的Factorial方法应该是类似这样的错误逻辑(虽然你没贴全代码,但结果已经暴露问题):

// 错误示例,仅用来展示问题
public int Factorial(int input) {
    int result = 1;
    for (int i = 0; i < input; i++) {
        result *= input; // 每次都乘输入的5,循环5次得到5*5*5*5*5=3125
    }
    return result;
}

这种写法是在计算输入值的N次方,完全偏离了阶乘的核心逻辑——阶乘需要从输入值开始,依次乘以比它小1的数,直到乘到1为止。

修复后的代码

这里给你两种常见的正确实现:

迭代版(推荐,避免递归栈溢出)

using System;
using System.Collections.Generic;
using System.IO;
public class Solution {
    public int Factorial(int input) {
        // 处理边界:负数没有阶乘,0和1的阶乘都是1
        if (input < 0)
            throw new ArgumentOutOfRangeException(nameof(input), "阶乘仅支持非负整数");
        if (input == 0 || input == 1)
            return 1;
        
        int result = 1;
        // 从input开始递减到1,依次相乘
        for (int i = input; i >= 1; i--) {
            result *= i;
        }
        return result;
    }
}

递归版(代码更简洁,但大数值可能触发栈溢出)

using System;
using System.Collections.Generic;
using System.IO;
public class Solution {
    public int Factorial(int input) {
        if (input < 0)
            throw new ArgumentOutOfRangeException(nameof(input), "阶乘仅支持非负整数");
        // 递归终止条件:0或1的阶乘为1
        return input <= 1 ? 1 : input * Factorial(input - 1);
    }
}

把你的Factorial方法替换成上面任意一种,再跑测试用例就能得到预期的120啦!

内容的提问来源于stack exchange,提问作者Ryan Archibald

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:08:37