2013-06-01 164 views
2

我需要生成隨機數從1到100,我知道該怎麼做一部分... ...生成隨機數1-100

我要問用戶他想要多少個號碼產生(如果他說5程序需要從1到100生成5個數字)。我只是現在如何通過在列表中添加新的int來進行修復。

我之前做到了這一點,但後來我無法使它工作,所以它會寫這些數字和最小+最大值的平均值。

這裏是我下面的代碼:

Random k = new Random(); 
//here i added in the same way other variables and put them in a list 
int j = k.Next(100); 

Console.WriteLine(""); 
double[] list1 = {j}; 
double povp = list1.Average(); 
Console.WriteLine(povp); 

Console.WriteLine(""); 
Console.WriteLine(list1.Max()); 
Console.WriteLine(""); 
Console.WriteLine(list1.Min()); 

Console.ReadKey(); 

回答

5

您可以使用下面的代碼來生成N個數:

IEnumerable<int> numbers = Enumerable.Repeat(1,N).Select(_ => random.Next(100)); 
+1

'100'是排他性的,而OP可能被問及包容性'100'。另外,當你不使用lambda參數時,最好將lambda參數記爲'_'。所以我會寫'.Select(_ => random.Next(101))' –

+0

我喜歡在這種情況下使用'_'的想法 - 開始學習Haskell。感謝您的建議。 – aquaraga

1
// ask user for input 
string input = Console.Readline(); 
int parsed; 
// parse to int, needs error checking (will throw exception when input is not a valid int) 
int.TryParse(input, out parsed); 

Random random = new Random(); 
List<double> list = new List<double>(); 

for(int i = 0; i < parsed; parsed++) 
{ 
    list.Add(random.Next(100)); 
} 
1
public void Main() 
     { 
      const int NUMBERS_FROM = 1; 
      const int NUMBERS_TO = 100; 

      int n = int.Parse(Console.ReadLine()); 
      Random rnd = new Random(); 
      List<int> numbers = new List<int>(); 

      for (int i = 0; i < n; i++) 
      { 
       int rndNumber = rnd.Next(NUMBERS_FROM, NUMBERS_TO + 1); 
       numbers.Add(rndNumber); 
      } 

      Console.WriteLine("Numbers : {0}",string.Join(", ",numbers)); 
     } 

這將產生N個號碼,並將其添加到一個列表,然後將它們打印到控制檯。我認爲這就是你要找的東西