我很难理解为什么这个功能表现不正确。
如果我输入num1 10的值和num2 20的值,则运行时,程序会告诉我10的值是20,实际上它不是。当我切换值并生成num1 20和num2 10时,它告诉我num1是num2的倍数 - 这是正确的。
如果有人能向我解释我哪里出错了,如果他们能告诉我代码的更正版本(如果可能的话),我们将不胜感激!
public class Multiple {
public static void main(String[]args) {
boolean multiple = true;
while(multiple = true) {
long num1 = 10;
long num2 = 20;
boolean result = isMultiple(num1, num2);
if (result = true) {
System.out.println(num1 + " is a multiple of " + num2);
} else {
System.out.println(num2 + " is not a multiple of " + num1);
}
break;
}
}
public static boolean isMultiple(long x, long y) {
if (x % y == 0) {
return true;
} else if (y % x == 0) {
return false;
}
return false;
}
}
答案 0 :(得分:1)
你的代码应该是:
public static void main(String[] args) {
boolean multiple = true;
while(multiple) {
long num1 = 10;
long num2 = 20;
boolean result = isMultiple(num1, num2);
if(result){
System.out.println(num1 + " is a multiple of " + num2);
} else {
System.out.println(num1 + " is not a multiple of " + num2);
}
break;
}
}
public static boolean isMultiple(long x, long y){
if (y%x == 0) {
return true;
}
return false;
}
如果不需要if和while,则更改= true。同样,对于第一个num是第二个数字,你需要第二个num%第一个数字。你不需要循环,但我认为你有它,因为你可能会在以后想要它,所以我保留它。
答案 1 :(得分:1)
行if (result = true)
实际上是设置 result
到true
。它应该更改为result == true
。我不确定while循环的用途,但我知道isMultiple
方法绝对可以简化。无论如何,我纠正了if
条件并做了一些其他的重构。
public class Multiple {
public static void main(String[] args) {
long num1 = 10;
long num2 = 20;
if (isMultiple(num1, num2)) {
System.out.println(num1 + " is a multiple of " + num2);
} else {
// num1 should come before num2 here
System.out.println(num1 + " is not a multiple of " + num2);
}
}
public static boolean isMultiple(long x, long y) {
// check that x is a multiple of y
return x % y == 0;
}
}
答案 2 :(得分:0)
public static void main(String[] args) {
boolean multiple = true;
while(multiple) {
long num1 = 10;
long num2 = 20;
boolean result = isMultiple(num1, num2);
if(result){
System.out.println(num1 + " is a multiple of " + num2);
} else {
System.out.println(num1 + " is not a multiple of " + num2);
}
break;
}
}
public static boolean isMultiple(long x, long y){
if (x<y) return false;
return (x % y == 0);
}