如何获取列表的产品?
How to take the Product of a List?
我正在尝试用 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();
将所有数字添加到列表中似乎没有太大好处,除非您需要这样做。
作为替代方案,类似这样的方法应该可行:
// 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;
}
您不需要列表来进行阶乘:
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();
我正在尝试用 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();
将所有数字添加到列表中似乎没有太大好处,除非您需要这样做。
作为替代方案,类似这样的方法应该可行:
// 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;
}
您不需要列表来进行阶乘:
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();