Java中如何对整数除法进行四舍五入并得到int结果? [复制]

2024-05-08

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


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

  • 这仍然比使用 abs() 避免双打要快。
  • 使用负数时结果是正确的,因为 -0.999 将向上舍入为 0

例子:

(int) Math.ceil((double)divident / divisor);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java中如何对整数除法进行四舍五入并得到int结果? [复制] 的相关文章

随机推荐