當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Double max()用法及代碼示例


Java Double 類的 max() 方法返回兩個 double 值中具有較大值的 double 對象。返回的結果與調用 Math.max() 方法相同。

用法

public static double max(double a, double b)

參數

這裏,a & b 是要比較的兩個操作數

返回值

max() 方法返回 a 和 b 中較大的值。

例子1

import java.util.Scanner;

public class Double_maxMethodExample1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter first number.");
        Double d1 = scanner.nextDouble();
        System.out.println("Enter second number");
        Double d2 = scanner.nextDouble();
        // return the greater of two values
        Double d3= Double.max(d1,d2);
        System.out.println("Enter third number");
        Double d4 =scanner.nextDouble();
        Double d5 =Double.max(d3,d4);
        System.out.println("The Max value is:"+d5);
    }
}

輸出:

Enter first number.
67
Enter second number
89.001
Enter third number
89.0011
The Max value is:89.0011

例子2

import java.util.Scanner;

public class Double_maxMethodExample2 {
    public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
        System.out.println("Enter total number of elements");
        int n = scanner.nextInt();
        // creating array
        Double a[] = new Double[n];
        System.out.println("Enter " + n + " elements");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextDouble();
        }
        Double d1 = 0.0;
        for (int i = 0; i < n - 1; i++) {
            // return the max of n numbers
            d1 = Double.max(a[i], a[i+1]);
            a[i+1] = d1;


            //System.out.println(d1);
        }
        System.out.println("Maximum value:" + d1);

    }
    
}

輸出:

Enter total number of elements
5
Enter 5 elements
90.009
98.887
67.8898
7566
77
Maximum value:7566.0

例子3

import java.util.Scanner;

public class Double_maxMethodExample3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of elements you want.");
        int n = scanner.nextInt();

        Double a[] = new Double[n];
        System.out.println("Enter elements");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextDouble();
        }
        Double f1, temp = 0.0;
        for (int i = 0; i < n ; i++) {
            for (int j = i+1; j < n; j++) {
                f1 = Double.max(a[i], a[j]);
                if (a[i].equals(f1)){
                    //temp = f1;
                    a[i] = a[j];
                    a[j] = f1;
                }
            }
        }
        System.out.print("Descending order = ");
        for (int i = n-1; i >=0; i--) {
            System.out.print(a[i]+",");
        }
    }
}

輸出:

Enter number of elements you want.
5
Enter elements
90.009
90.00008
90
89
89.999
Descending order = 90.009,90.00008,90.0,89.999,89.0,






相關用法


注:本文由純淨天空篩選整理自 Java Double max() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。