如何在整数除法和int结果在Java?

我刚刚写了一个很小的方法来计算手机短信的页数。 我没有select使用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.0000000。 有任何想法吗?

要整理一个整数除法,你可以使用

 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; } 

使用Math.ceil()并将结果转换为int:

  • 这仍然比通过使用abs()避免双打更快。
  • 使用底片时结果是正确的,因为-0.999会被舍入到0

例:

 (int) Math.ceil((double)divident / divisor); 

另一个不太复杂的单线:

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

可以使用long而不是int; 只是改变参数types和返回types。

 (message.length() + 152) / 153 

这会给出一个“向上取整”的整数。

 long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue(); 

Google的Guava库在IntMath类中处理 :

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

不同于这里的许多答案,它处理负数。 当尝试除以零时也会引发一个适当的例外。

对彼得的解决scheme进行扩展,这是我发现的作品,总是围绕“积极的无限”展开:

 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); } } 

如果你想计算一个除以b取整,你可以使用(a +( – a%b))/ b

这可能是有益的,减去余数到第十一个,并把它作为一个可分的数字,然后用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 

如果你想不导入任何东西,我build议这样做:

 int var = message.length() / 153; //you can put any integer instead of 153 depend on your case if(message.length() % 153 != 0) var = var + 1;