java类Math详解
Math类包含的方法
方法名 | 描述 |
---|---|
abs(double a) | 返回一个double值的绝对值 |
abs(float a) | 返回一个float 值的绝对值 |
abs(int a) | 返回一个int 值的绝对值 |
abs(long a) | 返回一个long 值的绝对值 |
addExact(int x, int y) | 返回参数x和y的和 超出int的长度会抛出异常ArithmeticException |
addExact(long x, long y) | 返回参数x和y的和 超出long 的长度会抛出异常ArithmeticException |
cbrt(double a) | 返回double值的立方根 |
ceil(double a) | 向上取整 |
floor(double a) | 向下取整 |
max(double a, double b) | 返回两个double 值中的较大者 |
max(float a, float b) | 返回两个float 值中的较大者 |
max(int a, int b) | 返回两个int 值中的较大者 |
max(long a, long b) | 返回两个long 值中的较大者 |
min(double a, double b) | 返回两个double 值中的较小者 |
min(float a, float b) | 返回两个float 值中的较小者 |
min(int a, int b) | 返回两个int 值中的较小者 |
min(long a, long b) | 返回两个long 值中的较小者 |
round(double a) | 返回四舍五入后的double值 |
round(float a) | 返回四舍五入后的float 值 |
double a = -1;
double b = Math.abs(a);//返回一个double 值的绝对值
结果:b = 1.0
float a = -1;
float b = Math.abs(a);//返回一个float 值的绝对值
结果:b = 1.0
int a = -1;
int b = Math.abs(a);//返回一个int 值的绝对值
结果:b = 1
long a = -1;
long b = Math.abs(a); //返回一个long 值的绝对值
结果:b = 1
int x = 1;
int y = 2;
int b = Math.addExact(x, y); //返回参数x和y的和 超出int的长度会抛出异常ArithmeticException
结果:b = 3
long x = 1;
long y = 2;
long b = Math.addExact(x, y); //返回参数x和y的和 超出long 的长度会抛出异常ArithmeticException
结果:b = 3
double a = 2;
double b = Math.cbrt(a); //返回double值的立方根
结果:b = 1.2599210498948732
double a = 2.12;
double b = Math.ceil(a); //向上取整
结果:b = 3.0
double a = 2.12;
double b = Math.floor(a); //向下取整
结果:b = 2.0
double a = 1;
double b = 2;
double c = Math.max(a, b); //返回两个double 值中的较大者
结果:c = 2.0
float a = 1;
float b = 2;
float c = Math.max(a, b); //返回两个float 值中的较大者
结果:c = 2.0
int a = 1;
int b = 2;
int c = Math.max(a, b); //返回两个int 值中的较大者
结果:c = 2
long a = 1;
long b = 2;
long c = Math.max(a, b); //返回两个long 值中的较大者
结果:c = 2
double a = 1;
double b = 2;
double c = Math.min(a, b); //返回两个double 值中的较小者
结果:c = 1.0
float a = 1;
float b = 2;
float c = Math.min(a, b); //返回两个float 值中的较小者
结果:c = 1.0
int a = 1;
int b = 2;
int c = Math.min(a, b); //返回两个int 值中的较小者
结果:c = 1
long a = 1;
long b = 2;
long c = Math.min(a, b); //返回两个long 值中的较小者
结果:c = 1
double a = 2.12;
double b = Math.round(a); //四舍五入
结果:b = 2.0
double a = 2.52;
double b = Math.round(a); //四舍五入
结果:b = 3.0
float a = 2.1;
float b = Math.round(a); //四舍五入
结果:b = 2.0
float a = 2.6;
float b = Math.round(a); //四舍五入
结果:b = 3.0