CodeGym /Java 博客 /随机的 /Java.lang.Math.max() 方法
John Squirrels
第 41 级
San Francisco

Java.lang.Math.max() 方法

已在 随机的 群组中发布
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