首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java中对整数除法进行四舍五入并得到int结果?

如何在Java中对整数除法进行四舍五入并得到int结果?
EN

Stack Overflow用户
提问于 2011-09-16 23:06:38
回答 8查看 166.4K关注 0票数 114

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

下面是我的代码:

代码语言:javascript
复制
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。有什么想法吗?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-09-16 23:09:50

要向上舍入整数除法,您可以使用

代码语言:javascript
复制
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);
}

或者如果两个数字都是正数

代码语言:javascript
复制
public static long roundUp(long num, long divisor) {
    return (num + divisor - 1) / divisor;
}
票数 132
EN

Stack Overflow用户

发布于 2013-11-20 16:00:36

另一个不太复杂的一行代码:

代码语言:javascript
复制
private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

可以使用long而不是int;只需更改参数类型和返回类型。

票数 51
EN

Stack Overflow用户

发布于 2017-01-25 02:39:32

谷歌的芭乐图书馆handles this in the IntMath class

代码语言:javascript
复制
IntMath.divide(numerator, divisor, RoundingMode.CEILING);

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

票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7446710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档