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

发布于 2024-12-05 00:26:29 字数 1102 浏览 2 评论 0原文

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

I just wrote a tiny method to count the number of pages for cell phone SMS. I didn't have the option to round up using Math.ceil, and honestly it seems to be very ugly.

Here is my code:

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

I don't really like this piece of code and I'm looking for a more elegant way of doing this. With this, I'm expecting 3 and not 3.0000000. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

半夏半凉 2024-12-12 00:26:29

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

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

示例:

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

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

  • This is still faster than to avoid doubles by using abs().
  • The result is correct when working with negatives, because -0.999 will be rounded UP to 0

Example:

(int) Math.ceil((double)divident / divisor);
一个人的旅程 2024-12-12 00:26:29

要对整数除法进行四舍五入,您可以使用

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

or 如果两个数字都是正数

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

To round up an integer division you can use

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

or if both numbers are positive

public static long roundUp(long num, long divisor) {
    return (num + divisor - 1) / divisor;
}
葬花如无物 2024-12-12 00:26:29

另一种不太复杂的单行:

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

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

Another one-liner that is not too complicated:

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

Could use long instead of int; just change the parameter types and return type.

墨落成白 2024-12-12 00:26:29

Google 的 Guava 库在 IntMath 类中处理此问题

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

与此处的许多答案不同,它处理负数。当尝试除以零时,它还会引发适当的异常。

Google's Guava library handles this in the IntMath class:

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

Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.

甜点 2024-12-12 00:26:29
(message.length() + 152) / 153

这将给出一个“向上舍入”的整数。

(message.length() + 152) / 153

This will give a "rounded up" integer.

梦毁影碎の 2024-12-12 00:26:29
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
仙女山的月亮 2024-12-12 00:26:29

如果你想计算 a 除以 b 向上取整,你可以使用 (a+(-a%b))/b

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

说不完的你爱 2024-12-12 00:26:29

扩展彼得的解决方案,我发现这对我来说总是可以围绕“正无穷大”:

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

Expanding on Peter's solution, this is what I've found works for me to always round 'towards positive infinity':

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);
    }
}
短暂陪伴 2024-12-12 00:26:29

这可能会有所帮助,,
将余数减去长度,使其成为可整除的数,然后除以 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 

this might be helpfull,,
Subtract the remainder to the legnth and make it a divisible number and then divide it with 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 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文