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


Java Float max()用法及代码示例


Java Float 类的 max() 方法返回两个浮点值之间具有较大值的浮点数。返回结果与调用 Math.max() 方法相同。

用法:

Public static float max(float a, float b)

参数:

这里,a & b 是要比较的两个操作数。

返回值:

max() 方法返回 a 和 b 之间的较大值。

例子1

import java.util.Scanner;

 public class FloatMaxExample1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter first number.");
        Float f1 = scanner.nextFloat();
        System.out.println("Enter second number");
        Float f2 = scanner.nextFloat();
       //return the greater of two values
        Float f3= Float.max(f1,f2);
        System.out.println("The Max value is:"+f3);
    }
}

输出:

Enter first number.
90.7658
Enter second number
90.84375
The Max value is:90.84375

例子2

import java.util.Scanner;

public class FloatMaxExample2 {
    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
        Float a[] = new Float[n];
        System.out.println("Enter " + n + " elements");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextFloat();
        }
        Float f3 = 0f;
        for (int i = 0; i < n - 1; i++) {
         // return the max of n numbers
            f3 = Float.max(a[i], a[i + 1]);
            f3 = Float.max(a[i], a[i+1]);
            a[i+1] = f3;

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

输出:

Enter total number of elements
4
Enter 4 elements
90.99
90.11
9
8
Maximum value:90.99

例子3

import java.util.Scanner;

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

        Float a[] = new Float[n];
        System.out.println("Enter elements");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextFloat();
                    }

        Float f1, temp = 0f;
        for (int i = 0; i < n ; i++) {
            for (int j = i+1; j < n; j++) {
                f1 = Float.max(a[i], a[j]);
                if (a[i].equals(f1)){
                    temp = f1;
                a[i] = a[j];
                a[j] = temp;
            }
            }
        }
        System.out.print("Ascending order = ");
        for (int i = 0; i < n; i++) {
            System.out.print(a[i]+",");
        }
    }
}

输出:

Enter number of elements you want.
5
Enter elements
90.99
98
123
11
2
Ascending order = 2.0,11.0,90.99,98.0,123.0,






相关用法


注:本文由纯净天空筛选整理自 Java Float max() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。