跳到主要内容

Java Math max()

max() 方法返回指定参数中的最大值。

示例

class Main {
public static void main(String[] args) {

// 计算 88 和 98 的最大值
System.out.println(Math.max(88, 98));

}
}

// 输出:98

Math.max() 的语法

max() 方法的语法是:

Math.max(arg1, arg2)

这里,max() 是一个静态方法。因此,我们通过类名 Math 来访问这个方法。

max() 参数

max() 方法接受两个参数。

  • arg1/arg2 - 在这些参数中返回最大值

注意:参数的数据类型应该是 intlongfloatdouble

max() 返回值

  • 返回指定参数中的最大值

示例 1:Java Math.max()

class Main {
public static void main(String[] args) {

// 使用 int 类型参数的 Math.max()
int num1 = 35;
int num2 = 88;
System.out.println(Math.max(num1, num2)); // 88

// 使用 long 类型参数的 Math.max()
long num3 = 64532L;
long num4 = 252324L;
System.out.println(Math.max(num3, num4)); // 252324

// 使用 float 类型参数的 Math.max()
float num5 = 4.5f;
float num6 = 9.67f;
System.out.println(Math.max(num5, num6)); // 9.67

// 使用 double 类型参数的 Math.max()
double num7 = 23.44d;
double num8 = 32.11d;
System.out.println(Math.max(num7, num8)); // 32.11
}
}

在上面的示例中,我们使用了 intlongfloatdouble 类型参数的 Math.max() 方法。

示例 2:从数组中获取最大值

class Main {
public static void main(String[] args) {

// 创建一个 int 类型的数组
int[] arr = {4, 2, 5, 3, 6};

// 将数组的第一个元素赋值为最大值
int max = arr[0];

for (int i = 1; i < arr.length; i++) {

// 与 max 比较所有元素
// 将最大值赋给 max
max = Math.max(max, arr[i]);

}

System.out.println("最大值:" + max);
}
}

在上面的示例中,我们创建了一个名为 arr数组。最初,变量 max

储数组的第一个元素。

这里,我们使用了 for 循环来访问数组的所有元素。注意这行代码,

max = Math.max(max, arr[i])

Math.max() 方法将变量 max 与数组的所有元素进行比较,并将最大值赋给 max

推荐教程