max()
方法返回指定参数中的最大值。
示例
class Main { public static void main(String[] args) { // compute max of 88 and 98 System.out.println(Math.max(88, 98)); } } // Output: 98
Math.max() 的语法
max()
方法的语法是:
Math.max(arg1, arg2)
这里,
max()
是一个静态方法。因此,我们使用类名访问该方法,
Math
。
max() 参数
max()
方法有两个参数。
注意: 参数的数据类型应该是int、long、float或double。
max() 返回值
返回指定参数中的最大值示例 1: Java Math.max()
class Main { public static void main(String[] args) { // Math.max() with int arguments int num1 = 35; int num2 = 88; System.out.println(Math.max(num1, num2)); // 88 // Math.max() with long arguments long num3 = 64532L; long num4 = 252324L; System.out.println(Math.max(num3, num4)); // 252324 // Math.max() with float arguments float num5 = 4.5f; float num6 = 9.67f; System.out.println(Math.max(num5, num6)); // 9.67 // Math.max() with double arguments double num7 = 23.44d; double num8 = 32.11d; System.out.println(Math.max(num7, num8)); // 32.11 } }
在上面的例子中,我们使用了
Math.max()
方法和
int
、
long
、
float
和
double
类型参数。
示例 2: 从数组中获取最大值
class Main { public static void main(String[] args) { // create an array of int type int[] arr = {4, 2, 5, 3, 6}; // assign first element of array as maximum value int max = arr[0]; for (int i = 1; i < arr.length; i++) { // compare all elements with max // assign maximum value to max max = Math.max(max, arr[i]); } System.out.println("Maximum Value: " + max); } }
在上面的示例中,我们创建了一个名为
arr 的 array。最初,变量
max 存储数组的第一个元素。
这里,我们使用了
for
循环来访问数组的所有元素。注意这一行,
max = Math.max(max, arr[i])
Math.max()
方法将变量
max 与数组的所有元素进行比较,并将最大值分配给
max。