cos()
方法的语法是:
Math.cos(double angle)
这里,
cos()
是一个静态方法。因此,我们使用类名访问该方法,
Math
。
cos() 参数
cos()
方法接受一个参数。
注意: 角度的值以弧度为单位。
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() 方法来计算一个数的平方根。