如何在整数除法和int结果在Java? [英] How to round up integer division and have int result in Java?

查看:222
本文介绍了如何在整数除法和int结果在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚写了一个微小的方法来计算手机短信的页数。我没有选择使用 Math.ceil ,实际上它看起来非常难看。



<这是我的代码:

  public class Main {

/ **
* @param args命令行参数
* /
public static void main(String [] args){
String message =今天我们偶然发现了一个巨大的性能泄漏,同时优化了光线投射算法令我们惊讶的是,Math.floor()方法花费了将近一半的计算时间:三层操作的时间与一个三线性插值的时间相同,因为我们不能相信地板方法能够产生如此丰满的效果开销,我们写了一个小的测试程序,重现;

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



code
$ b我不太喜欢这段代码,我正在寻找一个更优雅的方式来做到这一点。有了这个,我期待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);

$ / code $ / pre

如果两个数字都是正数

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


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?

解决方案

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

这篇关于如何在整数除法和int结果在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆