CodeGym /Java 博客 /随机的 /Java 中的 Math.cos() 方法
John Squirrels

San Francisco

# Java 中的 Math.cos() 方法

Java 中的Math类包含很多数学函数。三角函数是最重要的编程函数之一。其中一个函数是Math.cos()

## Java 中的 Math.cos() 方法

Math类的double cos (double x)方法返回x的余弦值，其中x是一个参数，以弧度为单位的角度。这是Java.lang.Math.cos()方法的声明：
``````
double cos(double x)
``````

``````
``````

``````
``````

``````
public class CosExample {
public static void main(String[] args) {

int x1 = 1;
double x2 = 0.5;
double x3 = Math.PI;

//using java.lang.Math.cos() for 1, 0.5 and PI rad

System.out.println("cosine of " + x1 + " rads = " + Math.cos(x1));
System.out.println("cosine of  " + x2 + " rads = " + Math.cos(0));
System.out.println("cosine  " + x3 + " rads = " + Math.exp(x3));

//here we declare an 60 degrees angle

double degree = 60;
//here we use Math.toRadians to convert 60 degrees to radians, use the cos() method
//to calculate the cosine of 60 degrees angle and print the result out
System.out.println("cosine of " + degree + " degrees = " + Math.cos(Math.toRadians(degree)));

}
}
``````

1 弧度的余弦 = 0.5403023058681398 0.5 弧度的余弦 = 1.0 余弦 3.141592653589793 弧度 = 23.140692632779267 60.0 度的余弦 = 0.5000000000000001

## 一些特殊情况

``````
public class CosSpecialCases {

public static void main(String[] args) {

double positiveInfinity = Double.POSITIVE_INFINITY;
double negativeInfinity = Double.NEGATIVE_INFINITY;
double nan = Double.NaN;

//The argument is positive infinity, the output is NaN
System.out.println(Math.cos(positiveInfinity));

//The argument is negative infinity, the output NaN
System.out.println(Math.cos(negativeInfinity));

//The argument is NaN, the output is NaN
System.out.println(Math.cos(nan));
}
}
``````

## 适合初学者的正弦和余弦任务

TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION