CodeGym /Java Blog /Toto sisi /Java.lang.Math.max() 方法
John Squirrels
等級 41
San Francisco

Java.lang.Math.max() 方法

在 Toto sisi 群組發布
Java Math 類包含進行數學計算所需的方法。我們需要的一種非常常見的計算是找到兩個數字的最大值。為此,java 引入了java.lang.Math.max()方法。關於lang.Math.max()方法,有一些關鍵的事情需要了解。它是一個靜態方法,因此,您將其與類名稱Math.max一起使用。此Math.max()方法只能採用兩個參數,因此您不能使用它在具有兩個以上數字的集合中查找最大值。它有四種重載方法,用於 int、double、float 和 long 數據類型。下面是 4 個方法的方法簽名。Java.lang.Math.max() 方法 - 1

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) 
讓我們在示例中使用這些方法中的每一種。尋找兩個整數的最大值。

public class Main   {  
    public static void main(String args[])  
    {  
        int x = 40;  
        int y = 60;    
        System.out.println(Math.max(x, y));  
    }  
} 
輸出將為 60。查找兩個雙精度值之間的最大值。

public class Main   {  
    public static void main(String args[])  
    {  
        double x = 15.68;  
        double y = -37.47;  
        System.out.println(Math.max(x, y));  
    }  
}
輸出將為 15.68 查找兩個浮點數之間的最大值。

public class Main   {  
    public static void main(String args[])  
    {  
        float x = -21.44f;  
        float y = -23.32f;  
        System.out.println(Math.max(x, y));  
    }  
}
輸出將為 -21.44f 最後,讓我們找出兩個 long 值之間的最大值。

public class Main   {  
    public static void main(String args[])  
    {  
        long x = 123456778;  
        long y = 453455633;    
        System.out.println(Math.max(x, y));  
    }  
}
輸出將為 453455633。雖然Math.max允許您給出兩個值,但您可以即興使用它來找到三個或更多值中的最大值。檢查以下示例。

public class Main   
{  
    public static void main(String args[])  
    {  
        int x = 40;  
        int y = 60;   
        int z = 75;
        //Find the maximum among three values using max() function
        System.out.println(Math.max(z, Math.max(x,y)));  
    }  
}
輸出將為 75。

結論

函數max()是 Java 中的一個簡單方法,非常易於使用。您所要做的就是將兩個值作為參數傳遞給該方法。Math 類屬於 java.lang 庫,默認在每個 java 應用程序中導入。因此,您無需導入任何內容即可使用Math.max()方法。
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION