Java max 函数

Java 的 max 函数是 Math 库函数之一,用于返回给定两个参数中的最大值。

Java 编程语言中 Math.max 的语法如下所示。

Math.max(data_type x, data_type y);
  • 如果参数是正整数或负整数,它将返回结果。
  • 如果我们提供正零和负零作为参数,max 函数将返回正零作为结果。
  • 此外,如果参数不是数字,它将返回 NaN。

Java 编程提供了四种不同的 Math.max 函数来查找两个给定 int 参数中的最大值。下面的函数将接受正整数或负整数作为第一个和第二个参数,并返回整数类型中的最大值。

static int max(integer x, intger y); //Return Type is Integer

// In order to use in program: 
Math.max(int x, int y);

类似地,下面的 math max 函数接受不同数据类型的负值或正值作为第一个和第二个参数。此函数将返回 double、float 和 long 数据类型中的最大值。

static double max(double x, double y); //Return Type is double
Math.max(double x, double y);

static float max(float x, float y); //Return Type is float
Math.max(float x, float y);

static long max(long x, long y); //Return Type is long
Math.max(long x, long y);

Java max 函数示例

在此示例中,我们使用 Math.max 函数查找不同数据类型中的最大值并显示输出。

在此示例中,首先,我们将该函数直接应用于正整数和负整数值。前三个 System.out.println 语句将调用整数类型(static int max(int a, int b))方法并找到值中的最大值。

在这里,我们对变量 b、c、d 和 e(它们属于 double 类型)使用了 Java Math.max 函数。以下三个语句将调用 double 类型的方法(static double max(double a, double b))并找到其中的最大值。

接下来,我们将其用于变量 g、h、i 和 j(它们属于 float 类型)。接下来的三行将调用 float 类型的方法(static float max(float a, float b))并找到最大值。

最后,我们将此 Math 函数用于变量 k、l、m 和 n(它们属于 long 类型)。最后三个语句将调用 long 类型的 max 函数。然后找到其中的最大值。

package MathFunctions;

public class MaxMethod {
 public static void main(String[] args) {
 double b = 10.9666, c = 14.6674, d = -9.474, e = -14.9865;
 float g = 1.23f, h = 4.809f, i = -7.89f, j = -6.54f;
 long  k = 200, l = 400, m = -300, n = -100;
 
 System.out.println("Maximum value of Positive Integer: " + Math.max(10, 20));
 System.out.println("Maximum value of Negative Integer: " + Math.max(-20, -60));
 System.out.println("Maximum value of both Positive & Negative: " + Math.max(10, -20));
 
 System.out.println("\nMaximum value of Positive Double: " + Math.max(b, c));
 System.out.println("Maximum value of Negative Double: " + Math.max(d, e));
 System.out.println("Maximum value of both Positive & Negative: " + Math.max(b, e));
 
 System.out.println("\nMaximum value of Positive Float: " + Math.max(g, h));
 System.out.println("Maximum value of Negative Float: " + Math.max(i, j));
 System.out.println("Maximum value of both Positive & Negative: " + Math.max(h, i));
 
 System.out.println("\nMaximum value of Positive Number: " + Math.max(k, l));
 System.out.println("Maximum value of Negative Number: " + Math.max(m, n));
 System.out.println("Maximum value of both Positive & Negative: " + Math.max(k, n));
 }
}
math max Function Example