2014-03-03 29 views
0

我寫了一個代碼,交換我的數組的第一個和最後一個值。 我得到它的工作,但由於某種原因,它不顯示數組的原始值。它只顯示交換的值。我希望它顯示原始值,並在底部顯示交換值。我做錯了什麼?請保持簡單,因爲我仍然對編碼感興趣。數組方法交換值

static void Main(string[] args) 
    { 
     int[] A = { 3, -12, 6, 9, -7, -13, 19, 35, -8, -11, 15, 27,-1 };  
     Console.WriteLine("\n=====================\n"); 
     Console.WriteLine("Swapping first and last element"); 
     SwapFirstAndLast(A); 
     DisplayArray(A); 
     //pause 
     Console.ReadLine(); 

    } 

    static void SwapFirstAndLast(int[] array) 
     { 
      int temp = array[0]; 
      array[0] = array[array.Length -1]; 
      array[array.Length - 1] =temp; 
     } 

    //method to display array 
    static void DisplayArray(int[] array) 
    { 
     Console.WriteLine("\n===========================\n"); 
     for (int i = 0; i < array.Length; i++) 
     { 
      Console.Write("{0} ",array[i]); 
     } 
     Console.WriteLine("\n===========================\n"); 
    } 
+6

你只在交換後調用'DisplayArray' - 你是否打算事先調用它?只需在前兩個'Console.WriteLine'調用之間添加'DisplayArray(A);'。 –

+0

@JonSkeet哦,我發現這非常有幫助,謝謝 – TheBoringGuy

+1

請不要在問題標題中包含有關語言的信息,除非在沒有它的情況下沒有意義。標籤用於此目的。 –

回答

2

正如喬恩說,你需要變異int[] A = { 3, -12, 6, 9, -7, -13, 19, 35, -8, -11, 15, 27,-1 };之前調用DisplayArray(A);

像這樣:

int[] A = { 3, -12, 6, 9, -7, -13, 19, 35, -8, -11, 15, 27,-1 }; 
Console.WriteLine("The array I want to change:"); 
DisplayArray(A); 
Console.WriteLine("\n=====================\n"); 
Console.WriteLine("Swapping first and last element"); 
SwapFirstAndLast(A); 
DisplayArray(A); 
//pause 
Console.ReadLine(); 

所有初學者和專業程序員:)常見錯誤。下一次,只需逐行瀏覽main方法,並對自己說這個特定的代碼行是什麼。如果它與你想要做的不一致,那麼現在你注意到有一個問題:)。

或者您可以使用兩個數組,說A這是你的輸入數組,分配AB,並使用SwapFirstAndLast(B),讓您同時擁有使用的突變和非突變陣列。

+0

「...和專業程序員」 我不同意。 :) –

+0

對於某些人來說,這個錯誤更爲明顯:p – theGreenCabbage

0

我建議你幾個改進過:

static void Main(string[] args) 
    { 
     int[] A = { 3, -12, 6, 9, -7, -13, 19, 35, -8, -11, 15, 27,-1 };  
     DisplayArray(A); 
     Console.WriteLine("\n=====================\n"); 
     Console.WriteLine("Swapping first and last element"); 
     SwapFirstAndLast(A); 
     DisplayArray(A); 
     //pause 
     Console.ReadLine(); 

    } 

    static void SwapFirstAndLast(int[] array) 
     { 
      //Equal than yours 
     } 

    //method to display array 
    static void DisplayArray(int[] array) 
    { 
     Console.WriteLine("\n===========================\n"); 
     Console.WriteLine(string.Join(",", array); 
     Console.WriteLine("\n===========================\n"); 
    } 

Console.WriteLine(的string.join(」」,數組);將讓你的輸出就會是這樣的:

3, -12,6,9,-7,-13,19,35,-8,-11,15,27,-1交換後

然後:

-1,-12,6,9 ,-7,-13,19,35,-8,-11,15,27,3