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。

猜你喜欢

转载自blog.csdn.net/lizengbao/article/details/85218404