Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中对整数除法进行取整并得到整数结果?_Java_Math_Types_Formatting - Fatal编程技术网

如何在Java中对整数除法进行取整并得到整数结果?

如何在Java中对整数除法进行取整并得到整数结果?,java,math,types,formatting,Java,Math,Types,Formatting,我刚刚写了一个计算手机短信页数的小方法。我没有选择使用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 optimi

我刚刚写了一个计算手机短信页数的小方法。我没有选择使用
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);
        }
    }
}
公共类主{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
String message=“今天,我们在优化光线投射算法时偶然发现了一个巨大的性能漏洞。让我们大吃一惊的是,Math.floor()该方法占用了几乎一半的计算时间:3个floor操作占用的时间与一个三线性插值相同。由于我们无法相信floor方法会产生如此巨大的开销,因此我们编写了一个小的测试程序,该程序可以重现“三次插值”;
System.out.printf(“计数为%d”,(int)messagePageCount(message));
}
公共静态双消息页面计数(字符串消息){
if(message.trim().isEmpty()| | message.trim().length()=0){
返回0;
}否则{
if(message.length()

这将给出一个“四舍五入”整数。

要将整数除法四舍五入,可以使用

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);
}
或者如果两个数字都是正数

public static long roundUp(long num, long divisor) {
    return (num + divisor - 1) / divisor;
}
这可能会有帮助,, 将余数减去整数,使之成为可除数,然后用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 

扩展彼得的解决方案,这就是我发现对我来说总是围绕“正向无限”的东西:

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);
    }
}
使用
Math.ceil()
并将结果强制转换为int:

  • 这仍然比使用abs()避免双打更快
  • 使用负片时,结果是正确的,因为-0.999将四舍五入为0
例如:

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

另一个不太复杂的班轮:

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

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

如果要计算a除以b的四舍五入值,可以使用(a+(-a%b))/b

谷歌的番石榴库:


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

我的意思是,尝试
num=-2
div=-3
。这将导致
-6/-3=2
但是
0666..
应该四舍五入到
1
。事实上,它对
num不起作用,我的编译器没有这样做“我不认识abs()-我不得不使用Math.abs()…@douglash,那是因为你错过了静态导入。在这(第2页)函数你需要num+除数-1@Peter Lawrey,如果你使用我提到的替代方法,它不会溢出。你的第一个函数等于带abs值的符号*第二个函数,所以没有什么复杂的地方。+1对于使用内置函数,这应该是答案。这可能是最容易实现的方法,不会执行任何额外的不必要的操作附加步骤。当转换为不同的数字类型时,它还避免了小的加法问题。很好的解决方案。感谢最有效和最简单的解决方案。这应该是正确的answer@DuaneOP说“我没有选择使用Math.ceil进行取整”的公平点,尽管我认为这是谷歌现在最受欢迎的“数学取整”:。可惜它有这样的条件。为什么我们需要在这样一个简单的计算中进行强制转换?Java应该提供一个更智能的API。这应该是正确的答案?包括浮点计算将不包括它的一些非直观的边缘情况和各种问题,只是为了取整简单的整数除法?通常是为了否定浮点问题人们使用double来代替,这只会使问题变得不那么突出,但不能解决问题。如果message.length()小于153,那该怎么办呢?你的想法很好,但我会解决这个问题:
(message.length()+(153-message.length()%153))/153
对于大多数业务代码,Math.ceil更具可读性。
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}
IntMath.divide(numerator, divisor, RoundingMode.CEILING);