JAVA之Math类的数学运算应用详解

来源:互联网 发布:双11淘宝报名入口 编辑:程序博客网 时间:2024/05/16 07:33

 Math类中定义了许多方法,这些方法都被定义为static形式,通过Math类可以在主函数中直接调用

调用方法:

Math.方法;

Math类中还定义了一些数学常量如:PI,E;

调用方法:

Math.PI;(PI表示π,即平角)

Math.E;

Math类方法:

1.三角函数方法:

double  sin(double a ) : 返回角的三角正弦

double cos(double a)  : 返回角的三角余弦

double tan(double  a)  : 返回角的三角正切

double asin(double a) : 返回角的反正弦

double acos(double a)  : 返回角的反余弦

double atan(double a)  : 返回角的反正切

double toRadians(double a) : 将角转换为弧度

doueble toDegrees(double a) : 将弧度转化为角

注意:

以上方法除了toRadians()外,参数均为double型,即以弧度代替角度来实现;

toRadians()则以角度为参数。

eg:

package Number;public class IntFunction {public static void main (String []args){System.out.println("90度的正弦值:" + Math.sin(Math.PI/2));System.out.println("0度的余弦值:" + Math.cos(0));System.out.println("60度的正切值:" + Math.tan(Math.PI/3));System.out.println("2的平方根与2商的反正弦值: " + Math.asin(Math.sqrt(2)/2));System.out.println("2的平方根与2商的反余弦值: " + Math.acos(Math.sqrt(2)/2));System.out.println("1的反正切值: " + Math.atan(1));System.out.println("120度的弧度值:" + Math.toRadians(120));System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI/2));System.out.println(Math.PI);}}
2.指数函数方法:

double exp(double a) : 用于获取e的a次方;

double log(double a) : 即lna;
double log10(double a) : 即log10a;

double sqrt(double a ):用于取a的平方根;

double cbrt(double a) : 用于取a的立方根;

double pow(double a, double b) : 用于求a的b次方;

eg:

package Number;public class IntFunction {public static void main (String []args){System.out.println("e的平方值: " + Math.exp(2));System.out.println("以e为底2的对数值:" + Math.log(2));System.out.println("以10为底2的对数值:" + Math.log10(2));System.out.println("4的平方根值:" + Math.sqrt(4));System.out.println("8的立方根值: " + Math.cbrt(8));System.out.println("2的2次方值: " + Math.pow(2, 2));}}

3.取整函数方法:

double ceil(double a):返回大于等于a的整数值,返回值类型为double;

double floor(double a) : 返回小于等于a的整数值,返回值类型为double;

double rint(double a) : 返回与a最接近的整数值,返回值类型为double;(如果两个同为整数且同样接近,选取偶数值的那个)

int round(double a ): 其值等于Math.floor(a + 0.5),返回值类型为long;

long round(float a ): 其值等于Math.floor(a + 0.5),返回值类型为int;

eg:

package Number;public class IntFunction {public static void main (String []args){System.out.println("使用ceil()方法取整: " + Math.ceil(5.2));//6.0System.out.println("使用floor()方法取整" + Math.floor(2.5));//2.0System.out.println("使用rint()方法取整: " + Math.rint(2.7));//3.0System.out.println("使用rint()方法取整: " + Math.rint(2.5));//2.0System.out.println("使用round()方法取整: " + Math.round(3.4f));//3System.out.println("使用round()方法取整: " + Math.round(2.5));//3System.out.println("使用round()方法取整: " + Math.round(-2.5));//-2System.out.println("使用round()方法取整: " + Math.round(-4.3));//-4}}/**输出结果:*使用ceil()方法取整: 6.0*使用floor()方法取整2.0*使用rint()方法取整: 3.0*使用rint()方法取整: 2.0*使用round()方法取整: 3*使用round()方法取整: 3*使用round()方法取整: -2*使用round()方法取整: -4*/