【发布时间】:2020-10-27 11:47:39
【问题描述】:
我正在编写一个代码,您可以从数组“b”中减去数组“a”的各个元素,直到数组“a”中的所有元素都相等。
条件是 a[i]>b[i] 进行减法。
但并非每次都可以使所有元素相等,所以在这种情况下,我希望我的代码打印'-1',我该如何实现它。
我真的很努力想出来,不要给出复杂的解决方案,因为我是初学者。你可以减去多少次。
Scanner sc = new Scanner(System.in);
short n = sc.nextShort();
short a[] = new short[n];
short b[] = new short[n];
for (short i = 0; i < n; i++) {// taking elements input
a[i] = sc.nextShort();
}
for (short i = 0; i < n; i++) {// taking elements input
b[i] = sc.nextShort();
}
short minimumOfArraya = 0;
for (short i = 0; i < n; i++) {// finding smallest element in array 'a'
for (short j = 0; j < n; j++) {
if (a[i] < a[j]) {
minimumOfArraya = a[i];
}
}
}
boolean allequal = false;
int counter = 0;
while (!allequal) {
for (short i = 0; i < n; i++) {// subtracting elements
if (a[i] == minimumOfArraya)
continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
counter++;
}
}
for (short i = 0; i < n; i++) {
if (a[0] == a[i]) {
allequal = true;
} else {
allequal = false;
break;
}
}
}
for (int i = 0; i < n; i++) {// printing array 'a'
System.out.print(a[i] + " ");
}
System.out.println();
System.out.println(counter);
4
5 7 4 3//infinite loop
4 1 0 0
working input
5
5 7 10 5 15
2 2 1 3 5
output
5 5 5 5 5
8
【问题讨论】:
-
请提供示例输入在哪里可以工作,哪里不能工作。
-
@Yunnosch 在我提到的情况下,你永远无法让所有元素都相等,因为 5 - 4 永远不会给出 3,所以在这种情况下,我想跳过循环。
-
好像不需要while,好像第一次迭代不成功,会陷入死循环
-
@Steyrix 不,可能还有其他不应该进入 while 循环的情况。
-
您能否提供一个示例输入,它会产生超过 1 次
while循环迭代并且不会导致无限循环