Java 常用类 Math类的使用教程

一、Java常用类Math类的用法

1.输出Π的值:

System.out.println("圆周率Π的值为:" + Math.PI);
//圆周率Π的值为:3.141592653589793

2.三角函数运算:

   System.out.println("圆周率Π的值为:" + Math.PI);
   System.out.println("sin(90')=" + Math.sin(Math.PI / 2));
   System.out.println("con(0)=" + Math.cos(0));

输出:
圆周率Π的值为:3.141592653589793
sin(90’)=1.0
con(0)=1.0

3.指数运算 对数运算

  System.out.println("e 的平方跟: " + Math.exp(2));
  System.out.println("以e为底的2的对数值ln2 : " + Math.log(2));
  System.out.println("以10为底的2的对数log10'2 : " + Math.log10(2));
  System.out.println("4的平方根 : " + Math.sqrt(4));
  System.out.println("8开3次方 :" + Math.cbrt(8));
  System.out.println("2 的 5次方 : " + Math.pow(2, 5));

输出:
e 的平方跟: 7.38905609893065
以e为底的2的对数值ln2 : 0.6931471805599453
以10为底的2的对数log10’2 : 0.3010299956639812
4的平方根 : 2.0
8开3次方 :2.0
2 的 5次方 : 32.0

4.比较运算

   System.out.println("取最大值 : " + Math.max(2, 3));
   System.out.println("取最小值: " + Math.min(2, 3));
   System.out.println("取绝对值: " + Math.abs(-1));

输出:
取最大值 : 3
取最小值: 2
取绝对值: 1

5.四舍五入运算


System.out.println("use floor 取整数 : " + Math.floor(2.5));
System.out.println("use round 四舍五入 : " + Math.round(2.5));
System.out.println("------------------ps-----------------");
System.out.println("***ps:  Math.round (x)=(int)Math.floor(x+o.5f) ***  ");
System.out.println(Math.round(2.5));
System.out.println(Math.round(-2.5));
System.out.println(Math.round(-2.51));
System.out.println(Math.floor(-2.5 + 0.5f));//-2.5+0.5=-2>=-2***其会得到一个小于等于-2的值
System.out.println(Math.floor(-2.51 + 0.5f));//-2.51+0.5=-2.01>=-3
//在正数的开运算中也是如此

输出:
use floor 取整数 : 2.0
use round 四舍五入 : 3
------------------ps-----------------
***ps: Math.round (x)=(int)Math.floor(x+o.5f) ***
3
-2
-3
-2.0
-3.0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章