Math.abs(-12);//求绝对值结果为12;
Math.ceil(12.46);//求大于等于参数的最小整数值,结果为13.0;
Math.floor(12.56);//求小于等于参数的最大整数值,结果为12.0;
Math.max(12,23);//求两者中的最大值,结果为23;
多重调用:Math.max(Math.max(12,23),47);//结果为47;
Math.min(12,23);//求两者中的最小值,结果为12;
Math.pow(2,3);//求幂,第一个数为底数,第二个数为指数,结果为2^3=8.0;
Math.pow(5,5);//求幂,第一个数为底数,第二个数为指数,结果为2^3=3125.0;
Math.sqrt(16);//求平方根,最后求得结果为4.0;
Math.round(12.34f);//求四舍五入Int类型,当舍入结果为正则5向上取整,当舍入结果为负则5向下取整。
具体分析过程如下:
(包含Int round(float val)函数与long round(double val))
public class MathTest {
public static void main(String[] args) { System.out.println("小数点后第一位=5");
System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));
System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));
System.out.println();
System.out.println("小数点后第一位<5");
System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));
System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));
System.out.println();
System.out.println("小数点后第一位>5");
System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));
System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));
}
}
运行结果:
1、小数点后第一位=5
2、正数:Math.round(11.5)=12
3、负数:Math.round(-11.5)=-11
4、
5、小数点后第一位<5
6、正数:Math.round(11.46)=11
7、负数:Math.round(-11.46)=-11
8、
9、小数点后第一位>5
10、正数:Math.round(11.68)=12
11、负数:Math.round(-11.68)=-12
根据上面例子的运行结果,我们还可以按照如下方式总结,或许更加容易记忆:
1、参数的小数点后第一位<5,运算结果为参数整数部分。
2、参数的小数点后第一位>5,运算结果为参数整数部分绝对值+1,符号(即正负)不变。
3、参数的小数点后第一位=5,正数运算结果为整数部分+1,负数运算结果为整数部分。
终结:大于五全部加,等于五正数加,小于五全不加。
Math.round
语法:
Math.round(x);
参数:
x 为一数值。
解释:
方法。返回对参数x四舍五入后所得的整数近似值。
round
public static long round(double a)
返回最接近参数的 long
。结果将舍入为整数:加上 1/2,对结果调用 floor 并将所得结果强制转换为long
(long)Math.floor(a + 0.5d)
特殊情况如下:
- 如果参数为 NaN,那么结果为 0。
- 如果结果为负无穷大或任何小于等于
Long.MIN_VALUE
- 的值,那么结果等于
Long.MIN_VALUE
- 如果参数为正无穷大或任何大于等于
Long.MAX_VALUE
- 的值,那么结果等于
Long.MAX_VALUE
参数:
a
- 舍入为 long
返回:
舍入为最接近的 long
round
public static int round(float a)
返回最接近参数的 int
。结果将舍入为整数:加上 1/2,对结果调用 floor 并将所得结果强制转换为int
(int)Math.floor(a + 0.5f)
特殊情况如下:
- 如果参数为 NaN,那么结果为 0。
- 如果结果为负无穷大或任何小于等于
Integer.MIN_VALUE
- 的值,那么结果等于
Integer.MIN_VALUE
- 如果参数为正无穷大或任何大于等于
Integer.MAX_VALUE
- 的值,那么结果等于
Integer.MAX_VALUE
参数:
a
返回:
舍入为最接近的 int