[英]This program that I am creating has to check to see if one number is a multiple of another number
This is what I have so far. 到目前为止,这就是我所拥有的。 If I put in a 4 for the first number and a 6 for the second it says that 4 is a multiple of 6,which is incorrect.
如果我在第一个数字中输入4,在第二个数字中输入6,则表示4是6的倍数,这是不正确的。 I am not sure what is going on with it.
我不确定这是怎么回事。
System.out.print("\n Name =");
String userName = console.readLine();
System.out.print("\n First Number =");
int firstNumber = console.readInt();
System.out.print("\n Second Number =");
int secondNumber = console.readInt();
if (firstNumber / secondNumber == 0 || secondNumber / firstNumber == 0) {
System.out.print("\n" + userName + "," + firstNumber + " is a multiple of " + secondNumber);
}
else {
System.out.print("\n" + userName + "," + firstNumber + " is not a multiple of " + secondNumber);
}
You can easily check if a number is a multiple of an other with a modulo. 您可以轻松地检查一个数是否是其他数与模的倍数。 Apply the module to the multiple you want to check, then simply confirm the remaining is equal to 0.
将模块应用于您要检查的倍数,然后简单地确认余数等于0。
Example : 范例:
int number = 3;
System.out.println("isMultiple : " + (number % 3 == 0));
As for what is wrong in your code, you divide and check if equals to 0, this is not the correct way to do. 至于代码中的错误,请划分并检查是否等于0,这不是正确的方法。
Look at this line 看这条线
firstNumber / secondNumber == 0
Replace firstNumber with 6 and secondNumber with 3, it will return 2 which won't be equals to 0 even if 3 is a multiple of 6. 将firstNumber替换为6,将secondNumber替换为3,它将返回2,即使3是6的倍数也将不等于0。
The simplest way to check if one number is a multiple of another is to use a modulo (remainder after division) operation. 检查一个数字是否是另一个数字的倍数的最简单方法是使用模(除法后的余数)运算。 So, the code might look like:
因此,代码可能类似于:
if(firstNumber % secondNumber == 0) {
// I'm a multiple!
}
Remember to check that secondNumber
is not zero, otherwise you'll run a into division by zero! 记住要检查
secondNumber
是否不为零,否则将被除以零!
Divide an int
by an int
give an int
, so 6/4 == 0
. 将一个
int
除以一个int
可得到一个int
,因此6/4 == 0
。
You can : 您可以 :
double
or float
, and check if the result is equals to itself casted as int
(or rounded) double
或float
,并检查结果是否等于转换为int
(或舍入)的自身 What is wrong is this check: firstNumber / secondNumber == 0
and the other one there. 这是什么错误的检查:
firstNumber / secondNumber == 0
,而另一个在那。 This is not how you correctly check if a number divides another number. 这不是您正确检查数字是否除以另一个数字的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.