Java学习-常用类(Math)

一、基本含义

Math类中的方法:都是static 型,需要类名直接调用。

1.1 随机数 ——Math.random()

语法:Math.random();
范围:[0,1)。
数据类型:double型。

// 要求:获取一个100以内的随机整数。
public int getRandomNumber(int length){
  return (int)(Math.random() * length);
}

1.2 四舍五入 ——Math.round()

语法:Math.round(数字);
本质:Math.floor(数字 + 0.5)。

Math.round(-11.5); // 结果:-11。
// 等价于=>
Math.floor(-11.5 + 0.5) // 结果:-11

1.3 向上取整 ——Math.ceil()

语法:Math.ceil(数字);

Math.ceil(-11.5); // 结果:-11。

1.4 向下取整 ——Math.floor()

语法:Math.floor(数字);

Math.ceil(-11.5); // 结果:-12。

1.5 次方 ——Math.pow()

语法:Math.pow(底数,次方);

Math.pow(2,3); // 结果:8。

1.6 算术平方根 ——Math.sqrt()

语法:Math.sqrt(数字);

Math.sqrt(4); // 结果:2。

1.7 最大最小 ——Math.max()

最大值语法:Math.max(数字);
最小值语法:Math.min(数字);

// 寻找数组中的最大值。
public int findMax(int[] arr){
  int max = arr[0];
  for(int i = 0; i < arr.length; i++){
    max = (int)(Math.max(arr[i],arr[i+1])); // 选取较大者。
  }
  return max;  
}
// 寻找数组中的最大值。
public int findMax(int[] arr){
  int max = arr[0];
  for(int i = 0; i < arr.length; i++){
    max = arr[i] > arr[i+1] ? arr[i]:arr[i+1]; // 选取较大者。
  }  
  return max;
}

1.8 绝对值 ——Math.abs()

语法:Math.abs(数字);

Math.abs(2-4); // 结果:2。
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值