文章目录
Math基本介绍
- Math类包含用于执行基本数学运算的方法,如初等指数,对数,平方根和三角函数。
- Math类都是静态方法,所以可以直接调用
Math类常见方法应用案例
- abs——绝对值
- pow——求幂
- ceil——向上取整
- floor——向下取整
- round——四舍五入
- sqrt——求开方
- random——求随机数
- max——求两个数的最大值
- min——求两个数的最小值
package com.tao.math_;
/**
* Create By 刘鸿涛
* 2022/1/3 13:01
*/
public class MathMethod {
public static void main(String[] args) {
// 1. abs——绝对值
int abs = Math.abs(-9);
System.out.println(abs); //9
// 2. pow——求幂
double pow = Math.pow(2,3);
System.out.println(pow); //8
// 3. ceil——向上取整
double ceil = Math.ceil(3.0001);
System.out.println(ceil); //4.0
double ceil2 = Math.ceil(-3.0001);
System.out.println(ceil2); //-3
// 4. floor——向下取整
double floor = Math.floor(3.0001);
System.out.println(floor); //3.0
double floor2 = Math.floor(-3.0001);
System.out.println(floor2); //-4.0
// 5. round——四舍五入
double round = Math.round(22.222);
System.out.println(round); //22.0
double round2 = Math.round(22.55);
System.out.println(round2); //23.0
double round3 = Math.round(-22.2);
System.out.println(round3); //-22.0
// 6. sqrt——求开方
double sqrt = Math.sqrt(-9.0);
System.out.println(sqrt); //Nan,无结果
double sqrt2 = Math.sqrt(9.0);
System.out.println(sqrt2); //3.0
// 7. random——求随机数
// random 返回的是0 ~ 1 之间的
//思考:请写出获取 a - b 之间的随机整数,a , b均为正数,比如 2 ~ 7之间
//不再分析了,直接写答案
for(int i = 0; i < 10; i++){
System.out.println((int)(2 + Math.random() * (7 - 2 + 1)));
}
// 8. max——求两个数的最大值
int max = Math.max(4,5); //5
// 9. min——求两个数的最小值
int min = Math.min(4,5); //4
}
}