英文:
Subtracting elements of an array from another array
问题
我对此还不太熟悉,所以任何帮助都将不胜感激。
我正在尝试从数组'a'中减去数组'b'的元素(仅减法,不移除),条件是如果数组'a'的元素大于相应数组'b'的元素。
我没有得到所需的输出,它只是打印了我输入的数组。
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++) {// 取得元素输入
a[i] = sc.nextShort();
}
for (short i = 0; i < n; i++) {// 取得元素输入
b[i] = sc.nextShort();
}
short m = 0;
for (short i = 0; i < n; i++) {// 找到数组'a'中最小的元素
for (short j = 0; j < n; j++) {
if (a[i] < a[j]) {
m = a[i];
}
}
}
boolean allequal = false;
while (!allequal) {
for (short i = 0; i < n; i++) {// 减去元素
if (a[i] == m)
continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
}
}
for (short i = 0; i < n; i++) {
for (short j = 0; j < n; j++) {
if (a[i] == a[j]) {
allequal = true;
} else {
allequal = false;
}
}
}
}
for (int i = 0; i < n; i++) {// 打印数组'a'
System.out.print(a[i] + " ");
}
5
5 7 10 5 15
2 2 1 3 5
5 5 9 5 10
英文:
I am fairly new to this so any help would be appreciated.<br /><br /> I am trying to subtract elements of array 'b' from array 'a'( not removing but just subtracting) provided if the element of array 'a' is greater than the corresponding element of array 'b'.<br /><br />
I am not getting the required output its just printing the array I have entered
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 m = 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]) {
m = a[i];
}
}
}
boolean allequal = false;
while (!allequal) {
for (short i = 0; i < n; i++) {// subtracting elements
if (a[i] == m)
continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
}
}
for (short i = 0; i < n; i++) {
for (short j = 0; j < n; j++) {
if (a[i] == a[j]) {
allequal = true;
} else {
allequal = false;
}
}
}
}
for (int i = 0; i < n; i++) {// printing array 'a'
System.out.print(a[i] + " ");
}
5
5 7 10 5 15
2 2 1 3 5
5 5 9 5 10
答案1
得分: 3
你的程序没有进入 while 循环,因为你错误地在 while (allequal = false) {
中使用了 =
运算符,这是赋值,而不是比较。正确的形式应该是 allequal == false
,这可以重写为 !allequal
。我没有检查剩余的代码。
请注意,你应该使用好的集成开发环境(IDE),它可以防止你出现这种错误,并提供调试器,你可以轻松地自行发现问题。
英文:
Your program does not enter while loop since you mistakenly used =
operator in while (allequal = false) {
which is assignment, not comparison. The correct form would be allequal == false
which rewrites to !allequal
. I didn't checked remaining code.
Note you should use good IDE which would prevent you doing such bug and provide debugger from which you could easily discover yourself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论