除以 2 不会完全起作用。它仅在您有奇数个整数时才有效。
例如:
给我一个代表数组长度的整数:5
输入 5 个值
值 #0:1
价值#1:2
价值#2:3
价值#3:4
价值#4:5
您当前的数组:1 | 2 | 3 | 4 | 5 |
你的数组颠倒了:5 | 4 | 3 | 2 | 1 | 构建成功(总时间:11 秒)
现在,如果你要输入一个偶数整数,比如 6,就会发生这种情况:
给我一个代表数组长度的整数:6
输入 6 个值
值 #0:1
价值#1:2
价值#2:3
价值#3:4
价值#4:5
价值#5:6
您当前的数组:1 | 2 | 3 | 4 | 5 | 6 |
你的数组颠倒了:6 | 5 | 3 | 4 | 2 | 1 | 构建成功(总时间:5 秒)
源代码:
/* 编写一个程序,提示用户输入一个表示数组长度的整数,然后要求用户输入那么多值。将这些值存储在一个数组中并打印该数组。然后反转数组元素,使第一个元素成为最后一个元素,第二个元素成为倒数第二个元素,依此类推,旧的最后一个元素现在首先出现。不要只是颠倒它们的打印顺序;实际上改变了它们在数组中的存储方式。不要创建第二个数组;只需重新排列您拥有的数组中的元素。(提示:交换需要改变位置的元素。)当元素被反转后,再次打印数组。*/
包反转数组;
导入 java.util.Scanner;
公共类 ReversinganArray {
public static void main(String[] args) {
int i = 0;
Scanner input = new Scanner(System.in);
System.out.print("Give me an integer that would represent the length of an array: ");
int integer = input.nextInt();
int[] test = new int[integer];
System.out.println("Enter " + integer + " " + "value(s)");
while (i < integer) {
System.out.println("Value #" + i + ": ");
test[i] = input.nextInt();
i++;
}
System.out.print("Your current array: ");
i = 0;
while (i < integer) {
System.out.print(test[i] + " | ");
i++;
}
i = 0;
while (i <= integer / 2) {
int temp = test[i]; //a = b
test[i] = test[(integer - i - 1)]; //b = c
test[(integer - i - 1)] = temp;// c = a
i++;
}
System.out.println("");
System.out.print("Your array reversed: ");
i = 0;
while (i <= integer - 1) {
System.out.print(test[i] + " | ");
i++;
}
}
}
我碰巧试图自己解决这个问题......