不返回预期值的数字的阶乘

Factorial of a number not returning expected value

我正在尝试通过如下测试用例:

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);
    }

}

我的代码返回 3125,预期答案是 120。

我的代码在下面,我不确定为什么它不起作用。

using System;
using System.Collections.Generic;
using System.IO;

public class Solution
{
    public int Factorial(int input)
    {
        int result = 1;

        for (int i = 1; i <= input; i++)
        {
            result = result * input;
        }

        return result;
    }

}

我看过其他类似的例子,但由于我的学习困难,我很难理解它们,有人能帮忙吗

您应该在 for 循环中将结果乘以 i 而不是 input,如下所示:

for (int i = 1; i <= input; i++)
{
    result = result * i;
}

阶乘函数有错误。您正在使用输入而不是迭代器。应该这样重写:

using System;
using System.Collections.Generic;
using System.IO;

public class Solution
{
    public int Factorial(int input)
    {
        int result = 1;

        for (int i = 1; i <= input; i++)
        {
            result = result * i;
        }

        return result;
    }
}