【Java 常用类】(4)java.lang.Math的常用方法




前言

前面我们了解了包装类的用法,挺多都是和数字有关的。那这次我们学学Math类。

一、大纲

Math类见名知意,办好了用于执行基本数学运算的方法,如指数、对数、平方根、三角函数等等很多有用的数学方法。

Math类主要是一个工具类,所有方法都是静态的。直接类名就可以调用。
在这里插入图片描述

public final class Math extends Object

二、使用

1.字段

两个字段看一眼名字应该就知道了,一个是常数e,一个是pi。

System.out.println(Math.E); // 2.718281828459045
System.out.println(Math.PI); // 3.141592653589793

2.常用方法

2.1 绝对值

返回传入数字的绝对值。

System.out.println(Math.abs(-99)); // 99
System.out.println(Math.abs(-99.99)); // 99.99
2.2 开方

sqrt()用于开平方。
cbrt()用于开立方。
hypot()用于求直角三角形的斜边长度。

double sqrt = Math.sqrt(4); // 返回4的平方根
System.out.println(sqrt); // 2.0

double cbrt = Math.cbrt(8); // 返回8的立方根
System.out.println(cbrt); // 2.0

double hypot = Math.hypot(3, 4); // 返回直角三角形的斜边长度,也就是sqrt(x^2+y^2)
System.out.println(hypot); // 5
2.3 取接近值

有三种:1.取接近无穷大的浮点数。2.取最接近无穷小的浮点数。3.四舍五入

double ceil = Math.ceil(-4.1); // 返回最接近无穷大的浮点数。
System.out.println(ceil); // -4.0
double ceil2 = Math.ceil(4.1); // 返回最接近无穷大的浮点数。
System.out.println(ceil2); // 5.0

double floor = Math.floor(-4.1); // 返回最接近无穷小的浮点数
System.out.println(floor); // -5.0
double floor2 = Math.floor(4.1); // 返回最接近无穷小的浮点数
System.out.println(floor2); // 4.0

long round = Math.round(-4.1); // 四舍五入
System.out.println(round); // -4
long round2 = Math.round(4.1); // 四舍五入
System.out.println(round2); // 4

// rint()方法和round()方法一样是四舍五入
double rint = Math.rint(-4.1); // 四舍五入
System.out.println(rint); // -4
double rint2 = Math.rint(4.1); // 四舍五入
System.out.println(rint2); // 4
2.4 对数

以10为底,计算传入数的对数。

double log10 = Math.log10(100); // 返回以10为底的对数值
System.out.println(log10); // 2
2.5 两数大小比较

两个数字间的大小比较

int min = Math.min(1, 2); // 返回两数中较小的数
int max = Math.max(1, 2); // 返回两数中较大的数
System.out.println(min); // 1
System.out.println(max); // 2
2.6 计算n^m
double pow = Math.pow(2, 3); // 返回2的3次幂,即2^3
double pow2 = Math.pow(2, 4); // 返回2的4次幂,即2^4
System.out.println(pow);
System.out.println(pow2);
2.7 获取随机数
double random = Math.random();// 返回[0, 1)之间的随机数
double random2 = Math.random()*10;// 返回[0, 10)之间的随机数
System.out.println(random); // 输出一个大于等于0小于1的随机数
System.out.println(random2);
发布了86 篇原创文章 · 获赞 104 · 访问量 6614

猜你喜欢

转载自blog.csdn.net/weixin_44034328/article/details/103996249