javaAPI_Math类

Math类

1.概述 
Math类包含用于执行基本数学运算的方法,如初等指数,对数,平方根和三角函数等。

2.Math类常用的方法

(1).成员变量
public static final double PI;定义了一个π,也就是圆周率
public static final double E; 定义了一个e,也就是自然对数底

(2).常用成员方法
public static int abs(int a);求取一个数的绝对值
public static double ceil(double a):对一个小数进行向上取整
public static double floor(double a):对一个小数进行向下取整
public static int max(int a,int b);获取俩个数中的最大值
public static pow(double a,double b);a的b次幂
public static double random();在[0.0,1.0)之间获取随机数
public static int round(float a):四舍五入
public static double sqrt(double a):正平方根

相关代码测试:
public static void main(String[] args) {
System.out.println("PI value:"+Math.PI);
System.out.println("E value:"+Math.E);
System.out.println("---------------");
System.out.println("abs:"+Math.abs(-10));
System.out.println("ceil:"+Math.ceil(1.23));
System.out.println("floor:"+Math.floor(1.23));
System.out.println("get Max:"+Math.max(1, 2));
System.out.println("pow:"+Math.pow(2, 3));
System.out.println("random:"+Math.random());
System.out.println("random[1-100]:"+(int)(Math.random()*100+1));
System.out.println("round:"+Math.round(12.67));
System.out.println("sqrt:"+Math.sqrt(4));
}

//输出结果:(注意返回值类型)
PI value:3.141592653589793
E value:2.718281828459045
---------------
abs:10
ceil:2.0
floor:1.0
get Max:2
pow:8.0
random:0.8585025895842625
random[1-100]:44
round:13
sqrt:2.0


3.获取任意范围内的随机数案例

代码实现:
public static void main(String[] args) {
System.out.println(Test.getRandom(18, 87));
}

/**
* 获取任意范围以内的随机数
* @param int start:开始位置
* @param int end:结束位置
* @return int:获取的结果
* @author Administrator

*/
public static int getRandom(int start,int end){
int returnValue = 0;
if(start < end){
returnValue = (int) (Math.random() * (end - start + 1) ) + start;
}
return returnValue;
}

//注意:按照理论,应该校验开始值和结束值的大小关系。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值