CodeGym /Java Blog /Toto sisi /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