数组方法交换值



我写了一个交换数组的第一个和最后一个值的代码。我让它工作,但由于某种原因它不显示数组的原始值。它仅显示交换的值。我希望它显示原始值,并在底部显示交换值。我做错了什么?请保持简单,因为我仍然是编码新手,谢谢。

   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");
    }

正如乔恩所说,你需要在变异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输入数组,将A分配为B,并使用SwapFirstAndLast(B),因此您同时可以使用突变和非突变数组。

我也建议您进行一些改进:

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.连接(" ", 数组);将使你的输出将是这样的:

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

最新更新