一、基本常用的Math类方法
Math.abs( ) - 返回参数的绝对值。
参数可以是 int, float, long, double, short, byte类型
1 public static voidmain(String args[]){2 Integer a = -8;3 double d = -100;4 float f = -90;5
6 System.out.println(Math.abs(a)); //8
7 System.out.println(Math.abs(d)); //100.0
8 System.out.println(Math.abs(f)); //90.0
9 }
Math.max( $ , $ )、Math.min( $ , $ ) - 返回两个数的最大值、最小值
参数可以是 int, float, long, double类型(参数也可以是short,byte,但是返回类型会转成int)
1 public static voidmain(String[] args) {2
3 double a = 1;4 double b = 2;5 System.out.println(Math.max(a,b)); //2.0
6 System.out.println(Math.min(a,b)); //1.0
7 }
java Math.pow( $ , $ ) - 计算次方
java Math.pow()方法用于返回第一个参数的第二个参数次方。
public static voidmain(String args[]){double x = 11.635;double y = 2.76;
System.out.printf("e 的值为 %.4f%n", Math.E);
System.out.printf("pow(%.3f, %.3f) 为 %.3f%n", x, y, Math.pow(x, y));
}
/*输出结果:e 的值为 2.7183
pow(11.635, 2.760) 为 874.008*/
java Math.cbrt( ) - 开立方、Math.sqrt( )- 开平方
返回double类型
System.out.println(Math.sqrt(4.0));//输出2.0
System.out.println(Math.cbrt(8.0));//输出2.0
Java Math.log( ) 计算对数
Math.log() 方法用于返回参数的自然数底数的对数值。
1 public static voidmain(String args[]){2 double x =Math.E;3 double y = 2.76;
5 System.out.printf("e 的值为 %.4f%n", Math.E);6 System.out.printf("log(%.3f) 为 %.3f%n", x, Math.log(x));7 }
输出结果为:
e 的值为 2.7183log(e) 为 1.000 //log(e)=lne=1.0
Java Math.round( ) - 四舍五入
Java Math.round() 方法返回一个最接近的int、long型值。
1 public static voidmain(String args[]){2 double d = 100.675;3 double e = 100.500;4 float f = 100;5 float g =90f;6
7 System.out.println(Math.round(d)); //1018 System.out.println(Math.round(e)); //1019 System.out.println(Math.round(f)); //10010 System.out.println(Math.round(g)); //9011 }
Java Math.rint( ) - 就近取整
返回与参数最接近的整数。返回类型为double。
1 public static voidmain(String args[]){2 double d = 10.675;3 double e = 10.500;4 float f = 100;5 float g = 9.45;6
7 System.out.println(Math.round(d)); //11.0
8 System.out.println(Math.round(e)); //11.0
9 System.out.println(Math.round(f)); //100.0
10 System.out.println(Math.round(g)); //9.0
}
Java Math.floor( ) - 向下取整
Math.floor() 方法可对一个数进行下舍入,直接取整,返回给定参数最大的整数,该整数小于或等给定的参数。参数可以使double和float ,返回doublefloor:地板
ava Math.ceil( ) - 向上取整
Math.ceil() 就是向上取整,参数可以使double和float ,返回double。ceil:天花板
1 public static voidmain(String args[]){2 double d = 100.675;3 float f = -90;4
5 System.out.println(Math.floor(d));//100.06 System.out.println(Math.floor(f));//-90.07
8 System.out.println(Math.ceil(d));//101.09 System.out.println(Math.ceil(f));//-90.010 }
文章参考:http://www.51gjie.com/java/185.html & 菜鸟教程