循环乘以int以降低int

时间:2013-11-18 12:46:39

标签: c# for-loop multiplying

我有以下循环:

    public int multiply(int Z)
    {
        //Z=5
       for (int i = 1; i <= Z; i++)
        {
             int Y=Z*i;
             return Y;
           //i wanna Y multiply x*4*3*2*1 all loops in one result
        }
        return Z;
    }

我想知道该怎么做:

创建一个新的乘法int Y = Z * 4 * 3 * 2 * 1 乘法结果将在控制台写入行:

("value for your loop is " +test.multiply(5));
value for your loop is 120

这可以通过for循环完成,还是我错了?

5 个答案:

答案 0 :(得分:4)

这称为factorial

public int Factorial(int num)
{
    int factorial = 1;

    for (int i = 2; i <= num; i++)
    {
        factorial *= i;
    }

    return factorial;
}

Demo

你也可以递归获得阶乘(这是基本练习):

public int Factorial(int num)
{
    if (num <= 1)
        return 1;

    return num * Factorial(num - 1);
}

Demo

答案 1 :(得分:2)

我认为你的意思是你想要计算Z的阶乘。

public int Factorial(int Z)
{
    if (Z < 0) then return 0;

    int res = 1;
    for (int Y = 1; Y <= Z; Y++)
    {
        res *= Y;
    }
    return res;
}

答案 2 :(得分:1)

是:

public int multiply(int Z)
{
    int Y = Z;

    for (int i = Z; i > 0; i--)
    {
         Y *= i;
    }

    return Y;
}

答案 3 :(得分:1)

使用lambdas的因子:

Func<int, int> factorial = null;
factorial = x => x <= 1 ? 1 : x * factorial(x-1);
var result = factorial(10);

: - )

答案 4 :(得分:0)

public int multiply(int Z)
{
    int result = Z;
    for (int i = 1; i <= Z; i++)
    {
        int Z*=i;
    }
    return Z;
}