作为 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/