如何获取列表的产品?

时间:2015-07-10 15:33:48

标签: c# factorial

我正在尝试用C#制作一个因子计算器,但在将它们收集到一个列表中后,我很难将所有数字的乘积。

        List<int> myList = new List<int>();

        Console.WriteLine("My Job is to take the factorial of the number you give");
        Console.WriteLine("What is the number?");
        string A = Console.ReadLine();
        int C = Convert.ToInt32(A);
        T:
        myList.Add(C);
        C--;

        if (C == 0) goto End;
        goto T;
    End:
        // This is where the problem is,
        // i don't know of a way to take to product of the list "myList"
        //Any Ideas?
        int total = myList.product();
        Console.WriteLine(" = {0}", total);
        Console.ReadLine();

2 个答案:

答案 0 :(得分:0)

将所有数字添加到列表中似乎没什么好处,除非您需要这些数据。

作为替代方案,这样的事情应该有效:

// set product to the number, then multiply it by every number down to 1.
private int GetFactorial(int number)
{
    int product = number; 
    for (var num = number - 1; num > 0; num--) 
    {
        product *= num;
    }
    return product;
}

答案 1 :(得分:0)

您不需要列表来进行推理:

Console.WriteLine("My Job is to take the factorial of the number you give");
Console.WriteLine("What is the number?");
int c = Convert.ToInt32(Console.ReadLine());
int total = 1;

for (int i = 2; i < c; i++)
{
    total *= i;
}

Console.WriteLine(total.ToString());
Console.ReadLine();