使用 Java 中的 Math.max 獲取兩個數字的最大值
要使用 Java 中的 Math.max 獲取兩個數字的最大值,我們使用 java.lang.Math.max() 方法。Math.max() 接受兩個數字並返回較大的那個數字。該結果更接近於數軸上的正無窮大。即使其中一個值不是數字 (NaN),結果也是 NaN。
宣告 - java.lang.Math.max() 方法的宣告如下 −
public static int max(int a, int b) public static double max(double a, double b) public static long max(long a, long b) public static float max(float a, float b)
讓我們看一個程式,使用 Math.max() 方法獲取兩個數字的最大值
示例
import java.lang.Math;
public class Example {
public static void main(String[] args) {
// declaring and intializing some integer values
int a = 10;
int b = 9;
// declaring and intializing some float values
float c = 10.00f;
float d = 9.99f;
// declaring and initializing some double values
double x = 300.01d;
double y = 290.344d;
// declaring and initializing some long values
long r = 123456l;
long s = 35678l;
System.out.println("Maximum of " + a +" and " + b +" is " + Math.max(a,b));
System.out.println("Maximum of " + c +" and " + d +" is " + Math.max(c,d));
System.out.println("Maximum of " + x +" and " + y +" is " + Math.max(x,y));
System.out.println("Maximum of " + r +" and " + s +" is " + Math.max(r,s));
}
}輸出
Maximum of 10 and 9 is 10 Maximum of 10.0 and 9.99 is 10.0 Maximum of 300.01 and 290.344 is 300.01 Maximum of 123456 and 35678 is 123456
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP