如何舍入整数除法,并在 Java 中有整数结果?

我刚写了一个小方法来计算手机短信的页数。我没有选择使用 Math.ceil四舍五入,老实说,它似乎非常难看。

这是我的代码:

public class Main {


/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String message = "today we stumbled upon a huge performance leak while optimizing a raycasting algorithm. Much to our surprise, the Math.floor() method took almost half of the calculation time: 3 floor operations took the same amount of time as one trilinear interpolation. Since we could not belive that the floor-method could produce such a enourmous overhead, we wrote a small test program that reproduce";


System.out.printf("COunt is %d ",(int)messagePageCount(message));






}


public static double messagePageCount(String message){
if(message.trim().isEmpty() || message.trim().length() == 0){
return 0;
} else{
if(message.length() <= 160){
return 1;
} else {
return Math.ceil((double)message.length()/153);
}
}
}

我真的不喜欢这段代码,我正在寻找一种更优雅的方式来实现这一点。有了这个,我期待的是3,而不是3.000000。有什么想法吗?

193710 次浏览
(message.length() + 152) / 153

这将给出一个“四舍五入”的整数。

可以使用

import static java.lang.Math.abs;


public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}

或者两个数字都是正数

public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}

this might be helpfull,, 把余数减去长度,使它成为一个可整数,然后用153除以它

int r=message.length()%153;       //Calculate the remainder by %153
return (message.length()-r)/153;  // find the pages by adding the remainder and
//then divide by 153

在 Peter 的解决方案的基础上,我发现这个方法对我来说总是有效的:

public static long divideAndRoundUp(long num, long divisor) {
if (num == 0 || divisor == 0) { return 0; }


int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);


if (sign > 0) {
return (num + divisor - 1) / divisor;
}
else {
return (num / divisor);
}
}

Use Math.ceil() and cast the result to int:

  • 这仍然比使用 abs ()避免双精度要快。
  • 处理负数时,结果是正确的,因为 -0.999将四舍五入为0

例如:

(int) Math.ceil((double)divident / divisor);
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();

另一句不太复杂的俏皮话是:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

可以使用 long 代替 int; 只需更改参数类型和返回类型。

If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b

谷歌番石榴图书馆 handles this in the IntMath class:

IntMath.divide(numerator, divisor, RoundingMode.CEILING);

与这里的许多答案不同,它处理负数。当试图除以零时,它还会抛出一个适当的异常。