sin()
方法的语法是:
Math.sin(double angle)
这里,sin()
是一个静态方法。因此,我们通过类名 Math
来访问该方法。
sin() 参数
sin()
方法接受一个参数。
- angle - 需要返回其三角正弦的角
注意:angle 的值以弧度为单位。
sin() 返回值
- 返回指定 angle 的三角正弦
- 如果指定角度为NaN或无穷大,则返回NaN
注意:如果参数为零,则 sin()
方法的结果也为 零,并且符号与参数相同。
示例 1:Java Math sin()
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 sine value
System.out.println(Math.sin(a)); // 0.49999999999999994
System.out.println(Math.sin(b)); // 0.7071067811865475
// sin() with 0 as its argument
System.out.println(Math.sin(0.0)); // 0.0
}
}
在上面的示例中,我们导入了 java.lang.Math
包。导入该包是一个好习惯。注意表达式:
Math.sin(a)
这里,我们直接使用了类名来调用方法。这是因为 sin()
是一个静态方法。
注意:我们使用了 Java Math.toRadians() 方法将所有值转换为弧度。这是因为根据 Java 官方文档,sin()
方法将参数作为弧度。
示例 2:Math sin() 返回 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 sine value
System.out.println(Math.sin(a)); // NaN
System.out.println(Math.sin(infinity)); // NaN
}
}
在这里,我们创建了一个名为 a 的变量。
- Math.sin(a) - 返回 NaN,因为负数 (-5) 的平方根不是数字
Double.POSITIVE_INFINITY
是 Double
类的一个字段。它用于在 Java 中实现无穷大。
注意:我们使用了 Java Math.sqrt() 方法来计算数字的平方根。
另请阅读