cos()
方法的语法是
Math.cos(double angle)
这里,cos()
是一个静态方法。因此,我们使用类名 Math
来访问该方法。
cos() 参数
cos()
方法接受单个参数。
- angle - 要返回其三角余弦的角度
注意:angle 的值以弧度为单位。
cos() 返回值
- 返回指定角度的三角余弦
- 如果指定角度为NaN或无穷大,则返回NaN
示例 1:Java Math cos()
import java.lang.Math;
class Main {
public static void main(String[] args) {
// create variable in Degree
double a = 30;
double b = 45;
// convert to radians
a = Math.toRadians(a);
b = Math.toRadians(b);
// print the cosine value
System.out.println(Math.cos(a)); // 0.8660254037844387
System.out.println(Math.cos(b)); // 0.7071067811865476
}
}
在上面的示例中,我们导入了 java.lang.Math
包。如果我们想使用 Math
类的方法,这一点很重要。请注意表达式,
Math.cos(a)
在这里,我们直接使用类名调用了该方法。这是因为 cos()
是一个静态方法。
注意:我们使用了 Java Math.toRadians() 方法将所有值转换为弧度。这是因为根据官方文档,cos()
方法将角度视为弧度。
示例 2:Math cos() 返回 NaN
import java.lang.Math;
class Main {
public static void main(String[] args) {
// create variable
// square root of negative number
// results in not a number (NaN)
double a = Math.sqrt(-5);
// Using Double to implement infinity
double infinity = Double.POSITIVE_INFINITY;
// print the cosine value
System.out.println(Math.cos(a)); // NaN
System.out.println(Math.cos(infinity)); // NaN
}
}
在这里,我们创建了一个名为 a 的变量。
- Math.cos(a) - 返回 NaN,因为负数(-5)的平方根不是一个数字
Double.POSITIVE_INFINITY
是 Double
类的一个字段。它用于在 Java 中实现无穷大。
注意:我们使用了 Java Math.sqrt() 方法来计算数字的平方根。
另请阅读