2015-07-10 40 views
-5

我想在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

這是你可以乘HTTP://計算器.com/questions/19336150/how-to-multiply-all-elements-in-an-a-double-list,但你不需要這個因子,也可以搜索循環,並考慮避免goto。 – Habib

+4

使用循環代替'goto' – user1666620

+0

爲什麼要在第一個地方添加輸入列表?也避免使用'goto' –

回答

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(); 
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; 
} 
相關問題