请记住,我只想向下取最接近20的倍数,不会向上取整。
- 22 --> 20
- 45 --> 40
- 69.5 --> 60
- 60 --> 60
一种解决方案是从初始值中减去模20的结果(即除以20后的余数)。类似于以下内容:
double[] in = { 22, 45, 69.5, 60 };
for (double d : in) {
int v = (int) d;
v -= v % 20;
System.out.printf("%.1f --> %d%n", d, v);
}
输出结果为
22.0 --> 20
45.0 --> 40
69.5 --> 60
60.0 --> 60
public static Integer round20(Integer b){
return b - (b%20);
}
因此,您可以这样写:在计算机中,求余运算是指将一个数除以另一个数后得到余数的运算。
int unrounded = 66;
int rounded = unrounded - (unrounded % 20);
作为一种方法:
public static int moduloFloor(int toRound, int modulo) {
return toRound - (toRound % modulo);
}
你想知道提供的数字中有多少个20。假设x
是你的输入,请尝试以下方法:
Math.floor(x / 20) * 20
x - (x % 20)
的解答相比,这种方法更昂贵(减法比乘法更便宜/更快)。此外,使用 Math.floor() 函数速度较慢。 - frasnian