c# - 函数不返回反转数组

标签 c# arrays function return

作为 C# 的新手,我尝试使用一种方法来反转数组。但它不返回反向数组。我尝试了几个小时,但仍然不明白我做错了什么。整件事是我买的“The C# Players guide - 2nd edition”一书中的一课。不幸的是,书中没有包含类(class)的解决方案。 Main 方法是预定义的,应该像您看到的那样使用。

如果我在 for 循环中执行输出,它是 54321,这样就没问题了。但正确的输出应该来自 PrintNumbers 方法。并且存在问题,因为输出 12345 没有反转

这是代码,如果你看到什么不好的地方请告诉我。

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = GenerateNumbers();
        Reverse(numbers);
        PrintNumbers(numbers);

        Console.ReadKey();
    }

    //Generate the array and return the numbers
    static int[] GenerateNumbers()
    {
        int[] temp;
        temp = new int[] { 1, 2, 3, 4, 5 };
        return temp;
    }

    //Reverse the numbers in the array
    static int[] Reverse(int[] numbersToSwap)
    {
        //Write array length in value to decrement later
        int numbersLenghtMax = numbersToSwap.Length;
        //Minus 1 because an array starts with 0
        numbersLenghtMax--;

        //Create a temp value to store last value of array
        int[] temp = new int[numbersToSwap.Length];

        for (int index = 0; index < numbersToSwap.Length; index++)
        {
            //Store values reversed in the temp value
            temp[index] = numbersToSwap[numbersLenghtMax];
            numbersLenghtMax--;

            //This output is correct
            Console.Write(temp[index]);
        }
        Console.WriteLine();
        //The returned array is not reversed
        return temp;

    }

    //Print out the numbers
    static void PrintNumbers(int[] numbers)
    {
        foreach (int number in numbers)
            Console.Write(number);
    }
}

最佳答案

您的 Reverse 方法返回一个 int[](反转数组的结果),但您没有使用这样的返回值。

像这样使用它:

int[] numbers = GenerateNumbers();
numbers = Reverse(numbers); //Assign the return value to the numbers variable
PrintNumbers(numbers);

Console.ReadKey();

关于c# - 函数不返回反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729484/

相关文章:

c# - 如何使用远程数据将超链接配置到我的 Kendo UI TreeView 中?

c# - 使用 Uri 创建时,新 Runspace 对象的 SessionStateProxy 属性为空

c# - 方法中的多个 Linq.Tables

arrays - 通过 HTTP 将文件下载到 C# 中的字节数组中?

javascript - 使用 Javascript 计算数组中的重复值并返回带有附加值的计数

python - 在对每个数组进行更改时迭代数组列表

jquery - 如果函数不大于 1,则删除函数

c# - C# 中的 JQuery 样式 dom 操作

c - 数组的最大值的最大值

javascript - Rails - Turbolinks - 回调