java - 如何在 Java 中舍入整数除法并获得 int 结果?

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

最佳答案

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

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

例子:

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

https://stackoverflow.com/questions/7446710/

相关文章:

c - 如何在 C 中使用逗号作为千位分隔符来格式化数字?

c - 为什么 %d 代表整数?

mysql - 如何在 MySQL 数据库中存储电话号码?

java - 在 SimpleDateFormat 模式字符串中使用字母字符

java - 将 BigDecimal 格式化为最多 2 个十进制数字的字符串,在小数部分删除 0

python - 在 Python 中的文件末尾声明函数

excel - 如何在 Excel 中将单元格的字节格式设置为 KB、MB、GB 等?

objective-c - 将秒整数转换为 HH :MM, iPhone

sql - 从 SQL Server 中的十进制中删除尾随零

objective-c - Objective-C 中的舍入数字