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


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


Java.lang.math.max()函數是Java中的內置函數,該函數最多返回兩個數字。參數以int,double,float和long的形式接受,如果傳遞負數和正數作為參數,則生成正數結果。如果兩個參數傳遞的都是負數,那麽將生成幅度較小的數字。

用法:

dataType max(dataType num1, dataType num2)
The datatypes can be int, float, double or long.

參數: The function accepts two parameters num1 and num2 
among which the maximum is returned

返回值:該函數最多返回兩個數字。數據類型將與參數相同。


下麵給出的是函數max()的示例

// Java program to demonstrate the use of max() function 
// when two double data-type numbers are 
// passed as arguments 
public class Gfg { 
  
    public static void main(String args[]) 
    { 
        double a = 12.123; 
        double b = 12.456; 
  
        // prints the maximum of two numbers 
        System.out.println(Math.max(a, b)); 
    } 
}

輸出:

12.456
// Java program to demonstrate the use of max() function 
// when one positive and one negative 
// integers are passed as argument 
public class Gfg { 
  
    public static void main(String args[]) 
    { 
        int a = 23; 
        int b = -23; 
  
        // prints the maximum of two numbers 
        System.out.println(Math.max(a, b)); 
    } 
}

輸出:

23
// Java program to demonstrate the use of max() function 
// when two negative integers are passed as argument. 
public class Gfg { 
  
    public static void main(String args[]) 
    { 
        int a = -25; 
        int b = -23; 
  
        // prints the maximum of two numbers 
        System.out.println(Math.max(a, b)); 
    } 
}

輸出:

-23


相關用法


注:本文由純淨天空篩選整理自Twinkl Bajaj大神的英文原創作品 Java Math max() method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。