java两个数取最大值max,使用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) {

//声明和初始化一些整数值

int a = 10;

int b = 9;

//声明和初始化一些浮点值

float c = 10.00f;

float d = 9.99f;

//声明并初始化一些double值

double x = 300.01d;

double y = 290.344d;

//声明并初始化一些长值

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

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值