使用 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