Инструкции следующие:
"Создайте 3 метода: один для создания массива, один для изменения массива и один для печати массива в конце. Ваш основной метод будет выглядеть примерно так:
Код: Выделить всё
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
Reverse(numbers);
PrintNumbers(numbers);
}
Метод 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;
С учетом всего вышесказанного, вот мой код:
Код: Выделить всё
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?>
Подробнее здесь: https://stackoverflow.com/questions/532 ... doesnt-why
Мобильная версия