21xrx.com
2025-04-12 16:33:41 Saturday
文章检索 我的文章 写文章
JAVA中求最大值的方法及案例分享
2023-06-15 00:26:47 深夜i     15     0
Java 求最大值 if-else语句 Math

在Java中,求最大值是编程中常见的操作之一。本文将分享几种常见的方法和案例来帮助大家更好地理解Java中求最大值的方法。

方法一:使用if-else语句

通过比较每个数的大小,逐步确定最大值。

public static int getMax(int a, int b, int c){
  int max = a;
  if(b > max)
    max = b;
  
  if(c > max)
    max = c;
  
  return max;
}

方法二:使用Math.max()函数

Math.max()函数用于返回两个参数中较大的值。

public static int getMax(int a, int b, int c){
  int max = Math.max(a, b);
  max = Math.max(max, c);
  return max;
}

方法三:使用数组

将需要比较的数字放入数组中,遍历数组逐步确定最大值。

public static int getMax(int[] arr){
  int max = arr[0];
  for(int i = 1; i < arr.length; i++){
    if(arr[i] > max){
      max = arr[i];
    }
  }
  return max;
}

以上是几种常见的求最大值的方法,可以根据实际情况选择使用。接下来,我们将通过代码案例来演示Java中求最大值的方法。

案例一:求最大值

下面的代码演示了如何使用if-else语句来求三个数中的最大值。

public class MaxNumber {
  public static void main(String[] args) {
    int a = 18, b = 6, c = 15;
    int max = getMax(a, b, c);
    System.out.println("Max number is: " + max);
  }
  public static int getMax(int a, int b, int c){
    int max = a;
    if(b > max)
      max = b;
    
    if(c > max)
      max = c;
    
    return max;
  }
}

运行结果为:

Max number is: 18

案例二:使用Math.max()函数求最大值

下面的代码演示了如何使用Math.max()函数来求三个数中的最大值。

public class MaxNumber {
  public static void main(String[] args) {
    int a = 18, b = 6, c = 15;
    int max = getMax(a, b, c);
    System.out.println("Max number is: " + max);
  }
  public static int getMax(int a, int b, int c){
    int max = Math.max(a, b);
    max = Math.max(max, c);
    return max;
  }
}

运行结果为:

Max number is: 18

案例三:使用数组求最大值

下面的代码演示了如何用数组来求一组随机数字中的最大值。

public class MaxNumber {
  public static void main(String[] args) {
    int[] arr = 21;
    int max = getMax(arr);
    System.out.println("Max number is: " + max);
  }
  public static int getMax(int[] arr){
    int max = arr[0];
    for(int i = 1; i < arr.length; i++){
      if(arr[i] > max){
        max = arr[i];
      }
    }
    return max;
  }
}

运行结果为:

Max number is: 21

通过以上案例,我们可以看到求最大值的方法都比较简单,而且在实际编程中也经常用到。我们可以根据实际情况选择合适的方法来求最大值。

.max()函数、数组

  
  

评论区