Java rint 函数是 Math 库函数之一,它将指定的表达式或单个数字四舍五入到最近的数学整数。本文将通过一个示例展示如何使用 Math.rint 函数。
下面显示了 Java 编程语言中 Math.rint 函数的基本语法。
static double rint(double number); //Return Type is Double // In order to use in program: Math.rint(double number);
数字:它可以是 double 值或有效的数值表达式。
- 如果数字参数是正数或负数,此函数将返回最接近的值。
- 如果数字参数不是数字 (NaN)、无穷大、正零或负零,它将返回参数值作为结果。
Java Math.rint 函数示例
Math.rint 函数将 double 值四舍五入到最近的整数。在此 Java 程序中,我们将四舍五入正数和负数值并显示输出。
package MathFunctions;
public class RintMethod {
public static void main(String[] args) {
double a = Math.rint(140.456 - 34.9865 - 4.52);
System.out.println("Math.rint Result = " + a);
System.out.println("\nMath.rint Result of Positive Number: " + Math.rint(0.25));
System.out.println("Math.rint Result of Positive Number: " + Math.rint(12.05));
System.out.println("Math.rint Result of Positive Number: " + Math.rint(12.85));
System.out.println("\nMath.rint Result of Negative Number: " + Math.rint(-10.85));
System.out.println("RMath.rint Result of Negative Number: " + Math.rint(-10.25));
}
}

首先,我们声明一个 Double 类型的变量,并直接对表达式执行 rint 函数。
double a = Math.rint(140.456 - 34.9865 - 4.52);
System.out.println("Math.rint Result = " + a);
接下来,我们将此函数直接用于正 double 值。
System.out.println("\nMath.rint Result of Positive Number: " + Math.rint(0.25));
System.out.println("Math.rint Result of Positive Number: " + Math.rint(12.05));
System.out.println("Math.rint Result of Positive Number: " + Math.rint(12.85));
接下来,我们将Math 函数直接用于负 double 值。
System.out.println("\nMath.rint Result of Negative Number: " + Math.rint(-10.85));
System.out.println("RMath.rint Result of Negative Number: " + Math.rint(-10.25));
Java Math.rint 在数组上的示例
在此Java 程序中,我们找到批量数据的四舍五入值。在这里,我们将声明一个 double 类型的数组,并找到数组元素最接近(四舍五入)的值。
我们使用For Loop来迭代Java数组。在 For Loop 中,我们将 i 值初始化为 0。接下来,编译器将检查条件 (i < rintArray.length)。
提示:Array.length 查找给定数组的长度。
接下来,我们在 System.out.format 语句中直接使用 Math 函数。javac 编译器将调用静态 double rint(double number) 来查找相应的最接近值并打印输出。
package MathFunctions;
public class RintMethodOnArrays {
public static void main(String[] args) {
double [] rintArray = {-19.25, 110.98, 144.21, -120.59, -605.87, 38.4897};
for (int i = 0; i < rintArray.length; i++) {
System.out.println(Math.rint(rintArray[i]));
}
}
}
-19.0
111.0
144.0
-121.0
-606.0
38.0
Java Math.rint 在 ArrayList 上的函数示例
要查找单个项目的最接近值,请使用 Math.rint(myArray[index_position])。在此Java 程序中,我们将声明一个 double 类型的 ArrayList,并找到列表元素的最接近值。
首先,我们使用 For Loop 来迭代 ArrayList 中的 double 值。接下来,我们将 Math.rint 函数直接用于 System.out.format 语句。编译器将调用 math 方法(静态 double rint(double x))来查找相应的最接近值并打印输出。
package MathFunctions;
import java.util.ArrayList;
public class RintMethodOnList {
public static void main(String[] args) {
ArrayList<Double> myList = new ArrayList<Double>(5);
myList.add(-2.289);
myList.add(-2.65);
myList.add(Math.PI);
myList.add(59.05);
myList.add(33.568);
for (double x : myList) {
System.out.println(Math.rint(x));
}
}
}
-2.0
-3.0
3.0
59.0
34.0