In this guide, you will learn about the Java Math ceil() example method in Java programming and how to use it with an example.
1. Java Math ceil() example Method Overview
Definition:
The ceil() method of Java's Math class 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.
Syntax:
Math.ceil(a)
Parameters:
- a: A double value whose ceiling value is to be determined.
Key Points:
- If the argument is NaN, positive infinity, or negative infinity, then the result will be NaN, positive infinity, or negative infinity, respectively.
- If the argument value is already equal to a mathematical integer, then the result will be the same as the argument.
- The return type is double, even for whole number results.
2. Java Math ceil() example Method Example
public class CeilExample {
public static void main(String[] args) {
double[] values = {42.1, 42.7, -42.1, -42.7};
for (double value : values) {
// Calculate the ceiling value
double ceilValue = Math.ceil(value);
System.out.println("Ceiling value of " + value + ": " + ceilValue);
}
// Special case for NaN
System.out.println("Ceiling value of NaN: " + Math.ceil(Double.NaN));
}
}
Output:
Ceiling value of 42.1: 43.0 Ceiling value of 42.7: 43.0 Ceiling value of -42.1: -42.0 Ceiling value of -42.7: -42.0 Ceiling value of NaN: NaN
Explanation:
In the example:
1. For 42.1 and 42.7, their ceiling values are the next whole numbers, which are 43.0.
2. For negative numbers like -42.1 and -42.7, their ceiling values move closer to zero, resulting in -42.0.
3. The method returns NaN when passed NaN as an argument, adhering to the principle that operations with NaN generally result in NaN.
Comments
Post a Comment
Leave Comment