我是Java编程的新手,我尝试着不断学习。我遇到了一个问题,该问题源于我无法检查变量是否为整数。
int[] values = new int[3];
private Random rand = new Random();
num1 = rand.nextInt(70);
num2 = rand.nextInt(70);
num3 = rand.nextInt(70);
values[1] = num1 + num2
//we are dividing values[1] by num3 in order to produce an integer solution. For example (4 + 3) / 2 will render an integer answer, but (4 + 3) / 15 will not.
//The (correct) answer is values[2]
values[2] = values[1]/num3
if (num3 > values[1]) {
//This is done to ensure that we are able to divide by the number to get a solution (although this would break if values[1] was 1).
num3 = 2
while (values[2] does not contain an integer value) {
increase num3 by 1
work out new value of values[2]
}
} else {
while (values[2] does not contain an integer value) {
increase num3 by 1
work out new value of values[2] <--- I'm not sure if this step is necessary
}
}
System.out.println(values[2]);
最佳答案
如果将一个整数除以另一个整数,则将始终有一个整数。
您需要取模(余数)
int num1 = 15;
int num2 = 16;
int num3 = 5;
System.out.println("num1/num3 = "+num1/num3);
System.out.println("num2/num3 = "+num2/num3);
System.out.println("num1%num3 = "+num1%num3);
System.out.println("num2%num3 = "+num2%num3);
如果模数不为0,则结果将不是整数。