Java Math.round 函数

Java Math.round 函数是 Math 函数之一,用于将指定的表达式或单个数字四舍五入到最接近的整数。

Java 编程语言中 math.round 函数的基本语法如下所示。

Math.round(data_type number);

数字:它可以是数字或有效的数字表达式。

  • 如果数字参数为正或负,它将返回最接近的值。
  • 如果数字参数不是数字,它将返回零。

此程序提供了两个不同的函数来四舍五入指定的值。以下 math.round 函数将接受正数或负数的浮点值作为参数,并返回类型为 Int 的最接近的数学整数。

static int round(float number); //Return Type is Integer

// In order to use in program: 
Math.round(float number);

以下 round double 函数将接受正数或负数的双精度值,并返回类型为 long 的最接近的数学整数。

static long round(double number); //Return Type is Long

// In order to use in program: 
Math.round(double number);

Java Math.round 函数示例

我们使用此函数来四舍五入正值和负值,并显示输出。

package MathFunctions;

public class RoundMethod {
 public static void main(String[] args) {
 double a = Math.round(10.9666 - 14.9865 + 154.9852);

 System.out.println("Rounded value of Positive Number: " + Math.round(10.25));
 System.out.println("Rounded value of Positive Number: " + Math.round(10.95));
 
 System.out.println("\nRounded value of Negative Number: " + Math.round(-20.85));
 System.out.println("Rounded value of Negative Number: " + Math.round(-20.25));
 
 System.out.println("\nRounded value = " + a); 
 }
}
math.round Function 1

首先,我们声明一个 Double 类型的变量,并直接对表达式执行 round 函数。

double a = Math.round(10.9666 - 14.9865 + 154.9852);

Math.round(10.9666 – 14.9865 + 154.9852)

==> Math.round (150.9653) ==> 151

接下来,我们将 round Math 函数直接应用于正的双精度值。在最后两行,我们将函数直接应用于负的双精度值。

Java Math.round 数组示例

在此 程序中,我们查找批量数据的四舍五入值。在这里,我们将声明一个双精度类型的数组,并使用 math 函数查找数组元素最接近(四舍五入)的值。

package MathFunctions;

public class RoundMethodOnArray {
	public static void main(String[] args) {
		
		double [] myArray = {-10.69, 40.98, 44.21, -12.59, -65.87, 3.4897};

		for (int i = 0; i < myArray.length; i++) {
			System.out.println(Math.round(myArray[i]));
		}
	}
}

math round 函数输出

-11
41
44
-13
-66
3

在此示例中,我们声明了一个双精度类型的数组并为其分配了一些随机数。

double [] myArray = {-10.69, 40.98, 44.21, -12.59, -65.87, 3.4897};

我们使用 Java For Loop 迭代数组。在 For Loop 中,我们将 i 初始化为 0。接下来,编译器将检查条件 (i < myArray.length)。只要条件为真,for 循环内的语句就会执行。

提示:myArray.length 查找 Java 数组的长度。

for (int i = 0; i < myArray.length; i++) {

以下语句将打印输出。如果仔细观察代码片段,我们会发现在 System.out.format 语句中直接使用了 round 函数。

这里,编译器将调用 (static long round(double number)) 来查找相应的最接近(四舍五入)的值。

System.out.println("Rounded value of Array Element = " + Math.round(myArray[i]));

注意:要查找单个项的最接近(四舍五入)值,请使用:Math.round(myArray[index_position])

Java Math.round ArrayList 示例

在此 程序中,我们将声明一个双精度类型的 ArrayList 并查找列表元素的最接近值。

在此示例中,我们使用 For Loop 迭代 ArrayList 中的双精度值。如果仔细观察代码片段,我们会发现在 System.out.format 语句中直接使用了 Math round 函数。这里,编译器将调用 long 方法来查找相应最接近的值并打印输出。

package MathFunctions;

import java.util.ArrayList;

public class RoundMethodOnList {
 public static void main(String[] args) {
 
 ArrayList<Double> myList = new ArrayList<Double>(5);
 myList.add(-15.289);
 myList.add(-15.65);
 myList.add(25.986);
 myList.add(40.499);
 myList.add(40.589);
 
 for (double x : myList) {
 System.out.println(Math.round(x));
 }
 }
}

输出

-15
-16
26
40
41

评论已关闭。