2013-04-29 26 views
1

所以基本上我編寫一個代碼,其中用戶輸入數組的大小和數組生成隨機數,然後用戶將輸入2個索引將交換索引。我需要做什麼以獲得一個隨機生成的數組與用戶輸入,然後輸入兩個索引交換它們?

到目前爲止,我只得到了主要部分。請幫幫我。除了當我嘗試在交換索引數組上打印時,我得到了一切,它給了我一個錯誤。

using System; 
    class MainClass 
{ 
     public static void Main (string[] args) 
     { 
     int[] randomSizedArray; 
     string sizeOfArray; 
     int convertedSizeArray = -1; 
     Console.WriteLine ("Please Enter the Size of the Array Between 1-99"); 
     sizeOfArray = Console.ReadLine(); 
     convertedSizeArray = Int32.Parse(sizeOfArray); 
     ; 
     randomSizedArray= new int[convertedSizeArray]; 
     Random rnd = new Random(); 
     for (int i=0; i < convertedSizeArray; i++) { 

     randomSizedArray[i] = rnd.Next(1,99); 


     } 
      for (int i=0; i < convertedSizeArray; i++) 
{ 
    Console.WriteLine(randomSizedArray[i] + ""); 
} 
     string swapindex1; 
     string swapindex2; 
     int index1; 
     int index2; 
     Console.WriteLine("Please Enter Index to swap"); 
     swapindex1 = Console.ReadLine(); 
     index1 = Int32.Parse(swapindex1); 
     int temp = randomSizedArray[index1]; 
     Console.WriteLine ("Please Enter a Second Value to swap"); 
     swapindex2 = Console.ReadLine(); 
     index2 = Int32.Parse(swapindex2); 
     randomSizedArray[index1] = randomSizedArray[index2]; 
     randomSizedArray[index2] = temp; 
     Console.WriteLine(randomSizedArray[temp] + ""); 
    } 


} 

回答

1

所以說,你需要隨機數介於0和10

array = new int[convertedSizeArray]; 
for (int i=0; i < convertedSizeArray; i++) 
{ 
    array[i] = rnd.Next(11); 
} 

然後,你可以問兩個數字你問數組長度相同的方式切換他們

int temp = array[index1]; 
array[index1] = array[index2]; 
array[index2] = temp; 

如果你想打印一個int你必須做Console.WriteLine(randomSizedArray.ToString())Console.WriteLine(randomSizedArray + "")

A第二,如果你要打印的每個號碼你可以打印出來是這樣的:

for (int i=0; i < convertedSizeArray; i++) 
{ 
    Console.WriteLine(array[i] + ""); 
} 
+0

這就是我說,是啊...... – 2013-04-29 13:50:00

+0

所以陣列=新的INT [convertedSizeArray] (int i = 0; i Larryjohncarter 2013-04-29 13:50:11

+0

第二部分切換給定索引處的數字。您可以按照您詢問數組長度的相同方式從用戶那裏獲取兩個索引。我假設你將這些值存儲在'int index1'和2 – 2013-04-29 13:51:58

相關問題