简体   繁体   中英

Math.ceil and Math.rint methods returning same value

The Math.rint() and Math.ceil() methods return the same value, can anyone please explain why?
What is the difference between these methods? When to use Math.rint() and where to use Math.ceil() ?

public class BasicMathDemo {

    public static void main(String[] args) {

        double b = 43.74;
        System.out.println("The rint of "+ b +" is : "+Math.rint(b));
        System.out.println("The ceiling of " + b +" is: "+ Math.ceil(b));

    }
}

Output is:

The rint of 43.74 is : 44.0
The ceiling of 43.74 is: 44.0

Math.rint() rounds your number to the closest Integer. See

Math.ceil() rounds-up your number to the closest highier Integer. See

Math.floor() rounds-down your number to the closest lower Integer. See

Example:

float number = 3.38;
double rint = Math.rint(number); // This will return 3
double ceil = Math.ceil(number); // This will return 4
double floor = Math.floor(number); // This will return 3

They return the same value because that's how they were designed to work for the given example.

rint :

"Returns the double value that is closest in value to the argument and is equal to a mathematical integer."

and ceil :

"Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer."

as seen here .

So, in both cases, they round up. If you want to see an example of them returning different values use 43.4 - for example.

You would use them where they will give you the desired results. Ceiling will only give you a number greater than or equal to the passed value. On the other hand, it's possible to get a number less than the passed with rint .

假设数组[1.1,2.9] ceil给2,3 flo0r给1,2 rint给1,3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM