在Java中划分以获得下一个上限值

时间:2018-01-18 03:26:54

标签: java division integer-division

我正在划分两个整数x / y。说3/2。然后,虽然实际结果为1.5,但结果会得到1。好的,这很明显,因为它是int division。但是我希望将1.5舍入到下一个最高值而不是最低点。结果需要2。 (人们可以使用mod然后划分来编写简单的逻辑......但我正在寻找简单的基于Java的API)。有什么想法吗?

4 个答案:

答案 0 :(得分:2)

您可以使用ceil(天花板)功能: https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)

这将基本上四舍五入到最接近的整数。

答案 1 :(得分:1)

通常,您可以编写(x + y - 1) / y来获取x/y的四舍五入版本。如果是3/2,则会变为(3 + 2 - 1) / 2 = 4 / 2 = 2

答案 2 :(得分:0)

如果您可以将数据类型更改为double,则以下是最佳解决方案 -

double x = 3;
double y = 2;        
Math.ceil(Math.abs(x/y));

这将给你2.0

答案 3 :(得分:0)

import java.lang.Math;
//round Up   Math.ceil(double num)
//round Down Math.floor(double num)
public class RoundOff 
{
 public static void main(String args[])
 { //since ceil() method takes double datatype value as an argument
   //either declare at least one of this variable as double
    int x=3; 
    int y=2; //double y =2;

   //or at least cast one of this variable as a (double) before taking division
    System.out.print(Math.ceil((double)x/y)); //prints 2.0
   //System.out.print(Math.ceil(x/y));
 }
}