【发布时间】:2018-11-10 19:38:03
【问题描述】:
我正在阅读这本书“The C# Player's Guide”并进入“试试看!”数组章节中的部分。
说明如下:
"创建 3 种方法:一种用于创建数组,一种用于反转数组,另一种用于在末尾打印数组。您的 main 方法将如下所示:
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
Reverse(numbers);
PrintNumbers(numbers);
}
GenerateNumbers 方法应该返回一个包含 10 个数字的数组。
PrintNumbers 方法应该简单地使用 for 或 foreach 循环遍历数组,一次一个,并打印出其中的项目。
Reverse 方法将是最难的。试一试,看看你能做到什么。如果您遇到困难,这里有一些提示:
提示 1:要交换 2 个值,您需要将一个变量的值放在一个临时位置以进行交换:
//Swapping a and b.
int a = 3;
int b = 5;
int temp = a;
int a = b;
int b = temp;
提示 2:获取要交换的正确索引可能是一个挑战。使用 for 循环,从 0 开始一直到数组的长度 / 2。您在 for 循环中使用的数字将是要交换的第一个数字的索引,另一个将是数组的长度减去索引减去 1。这是为了说明数组是从 0 开始的。所以基本上,你将用 array[arrayLength - index - 1] 交换 array[index]。"
说了这么多,这是我目前的代码:
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
Reverse(numbers);
PrintNumbers(numbers);
}
// Generates array of numbers and returns array
static int[] GenerateNumbers()
{
int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return numbers;
}
// Reverses array to print backwards from 10 to 1
static void Reverse(int[] numbers)
{
for (int index = 0; index < numbers.Length; index++)
{
//swapping array indexes
int a = numbers[index];
int b = numbers.Length - index - 1;
//temp array temporarily holds value while swapping indexes
int temp = a;
a = b;
b = temp;
}
}
// Prints numbers in array after order has been reversed
static void PrintNumbers(int[] numbers)
{
for (int index = 0; index < numbers.Length; index++)
{
Console.WriteLine(numbers[index]);
}
Console.WriteLine();
}
我的代码再次以数字顺序而不是反向打印数组。这是书中反向方法的解决方案:
static void Reverse(int[] numbers)
{
// Initialize one index at the start of the array, and another
// at the end of the array. The index of the last item in the
// array is the length of the array - 1.
int firstIndex = 0;
int secondIndex = numbers.Length - 1;
while (firstIndex < secondIndex)
{
// To swap two numbers, we need to copy one value out
// to a safe place so that it doesn't get overwritten.
int temp = numbers[firstIndex];
numbers[firstIndex] = numbers[secondIndex];
numbers[secondIndex] = temp;
// Move on to the next pair.
firstIndex++;
secondIndex--;
}
}
奇怪的是他们使用 while 循环而不是 for 循环作为指令状态。
有人可以帮我了解我的代码哪里出了问题和/或如何翻译他们的 while 语句以用作我的 for 循环吗?
【问题讨论】:
-
您正在交换 a 和 b 但没有将它们放回数组中......
-
使用 Visual Studio 自带的 AWESOME Step Debugger 可以轻松解决这些谜题
-
另外,
a是您数组中的一个值,但b只是另一个值的索引。 -
除了下面给出的答案中的代码更正之外,请注意您的
for循环在每一步中的作用。尝试找出正确解决方案中while循环在哪个条件下结束,并将其与for循环结束的条件进行比较。如果您遇到困难,请像使用计算机一样自己练习您的代码(是的,您就是那台奴隶般地执行代码的计算机)。在你的桌子上使用几个对象并将它们排成一行(这就是你的阵列)。跟踪index变量(无论是在纸上还是在您的脑海中),然后盲目地执行您的代码。你会看到会发生什么;-) -
@elgonzo 我实际上就是这样做的哈哈......然后我复制了给出的示例,用于从使用单独文件中的数组的指令中反转顺序,以查看它们是否正确反转。但是,它不会将更改应用回数组。而且我不完全确定该怎么做。