2013-03-28 74 views
1

由於某種原因,這不會編輯輸入到其中的數組的大小,並且數據不會添加到輸入的數組中。數組值不變?

public static void RandomizeArray(int[] array) 
    { 
     int intRead; 
     int intReadSeed; 
     Random randomNum = new Random(); 
     Console.WriteLine("How many ints do you want to randomly generated?"); 
     intRead = Convert.ToInt32(Console.ReadLine()); 
     array = new int[intRead]; 
     Console.WriteLine("What's the maximum value of the randomly generated ints?"); 
     intReadSeed = Convert.ToInt32(Console.ReadLine()); 
     for (int i = 0; i < intRead; i++) 
     { 
      array[i] = (randomNum.Next(intReadSeed)); 
     } 
     Console.WriteLine("Randomization Complete.\n"); 
    } 
+2

注意:您應該使用'randomNum.Next(intReadSeed + 1)',否則最大值將小於'intReadSeed'。 – Guffa 2013-03-28 01:53:34

回答

6

當你傳遞數組這種方法,按值傳遞 - 也就是說,你犯了一個全新的變量,也指向同一個對象。如果你在你的方法中編輯變量array指向一個新的數組,它也不會讓另一個變量指向你的新數組 - 它仍然指向舊的數組。所以,當你回到你沒有這樣做,是通過了。

爲了解決這個問題,return array;在方法的結束,簽名更改從voidint[]任何編輯的array。或者你可以做out int[] array作爲參數,所以你通過引用傳遞並編輯它。

+0

@Anthony Pegram你是對的,brainfart。 – Patashu 2013-03-28 01:47:50

+0

在這種情況下,根本沒有使用輸入數組,所以如果選擇了第一個修復,那麼也刪除參數,如果使用第二個修復,那麼寫出'out'而不是'ref',就像Romoku建議的那樣他的回答。 – 2013-03-28 02:28:45

+0

在這種情況下,執行out []數組或更簡單地返回一個值會更有效嗎? – 2013-03-28 04:17:12

2

簡單修復聲明參數爲out

public static void RandomizeArray(out int[] array) 
{ 
    int intRead; 
    int intReadSeed; 
    Random randomNum = new Random(); 

    Console.WriteLine("How many ints do you want to randomly generated?"); 

    intRead = Convert.ToInt32(Console.ReadLine()); 
    array = new int[intRead]; 

    Console.WriteLine("What's the maximum value of the randomly generated ints?"); 
    intReadSeed = Convert.ToInt32(Console.ReadLine()); 

    for (int i = 0; i < intRead; i++) 
    { 
     array[i] = (randomNum.Next(intReadSeed)); 
    } 

    Console.WriteLine("Randomization Complete.\n"); 
} 

這樣,你可以把它叫做:

int[] array; 

RandomizeArray(out array); 

但是,它可能會更好只返回數組。

public static int[] GenerateRandomizedArray() 
{ 
    int intRead; 
    int intReadSeed; 
    Random randomNum = new Random(); 

    Console.WriteLine("How many ints do you want to randomly generated?"); 
    intRead = Convert.ToInt32(Console.ReadLine()); 
    var array = new int[intRead]; 

    Console.WriteLine("What's the maximum value of the randomly generated ints?"); 
    intReadSeed = Convert.ToInt32(Console.ReadLine()); 

    for (int i = 0; i < intRead; i++) 
    { 
     array[i] = (randomNum.Next(intReadSeed)); 
    } 

    Console.WriteLine("Randomization Complete.\n"); 

    return array; 
}