当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。