2014-03-06 100 views
0

我正在用c#中的隨機數填充一個數組,但是我無法讓它工作。c#在數組中添加隨機數

 int[,] array = new int[10, 5]; 
     int x, y; 
     x = 0; 
     y = 0; 

     while (y <= 5) 
     { 
      Random r = new Random(); 
      int rand = r.Next(-50, 50); 
      array[x, y] = rand; 

      if (x == 10) 
      { 
       x = 0; 
       y++; 
      } 
      x++; 

     } 
+1

將'Random r = new Random();'帶出while循環。否則,您每次都會重新播種相同的種子! – Baldrick

回答

4

使用嵌套for循環,這是很容易:

Random rnd = new Random(); 
for (int i = 0; i < 10; i++) 
{ 
    for (int j = 0; j < 5; j++) 
    { 
     array[i, j] = rnd.Next(-50, 50); 
    } 
} 

while循環不是可讀的,但它是正確的,但你應該改變,而(y <= 5)while (y < 5)否則你將得到一個IndexOutOfRangeException。你應該在循環外定義你的Random實例。

0
int[,] array = new int[10, 5]; 
int x = 0, y = 0; 

Random r = new Random(); 
while (y < 5) 
{  
    int rand = r.Next(-50, 50); 
    array [x, y] = rand; 

    x++; 
    if (x == 10) 
    { 
     x = 0; 
     y++; 
    } 
} 
0

你需要你改變,如果還是數組聲明

int[,] array = new int[11, 6]; 

也有其他問題,您需要創建隨機前而

 Random r = new Random(); 

     while (y <= 5) 
     { 

打印出來的值,您可用於

 for (int i = 0; i < array.GetLength(0); i++) 
     { 
      for (int j = 0; j < array.GetLength(1); j++) 
       Console.WriteLine(array[i, j]); 
     } 
0

Try t他:

int[,] array = new int[10, 5]; 


     Random rnd = new Random(); 

     for (int row = 0; row < 10; row++) 
     { 
      for (int col = 0; col < 5; col++) 
      { 
       array[row, col] = rnd.Next(-50, 50); 
      } 
     } 
0
int[,] array = new int[10, 5]; 
     int x, y; 
     x = 0; 
     y = 0; 

     while (y < 5) 
     { 
      Random r = new Random(); 
      int rand = r.Next(-50, 50); 
      array[x, y] = rand; 

      if (x == 9) 
      { 
       x = 0; 
       y++; 
      } 
      x++; 

     } 

讓我們來看看這是否正常工作。