[英]Trying to create a function that takes two long values and returns true if and only if the first value is a multiple of the second value
我很难理解为什么此功能行为不正确。
如果我将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;
}
}
您的代码应类似于:
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;
}
如果不需要,则更改= true。 同样,为了使第一个数字是秒的倍数,您需要输入第二个数字%第一个数字。 您不需要循环,但我认为您拥有循环,因为以后可能需要它,所以我保留了它。
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;
}
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.