English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico de Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Tratamento de Exceções Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java Math cos() 使用方法及示例

Java Math Mathematical Methods

Java Math cos()方法返回指定角度的三角余弦。

cos()方法的语法为:

Math.cos(double angle)

cos()参数

  • angle - 要返回其三角余弦的角度

Note:angle的值以弧度为单位。

cos()返回值

  • 返回指定角度的三角余弦

  • 如果指定的角度为NaN或无穷大,则返回NaN

示例1:Java Math cos()

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //创建度数变量
    double a = 30;
    double b = 45;
    // 转换为弧度
    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()是静态方法。

Note:我们已经使用Math Radians()方法将所有值转换为弧度。 这是因为根据官方文档,cos()方法将角度作为弧度。

示例2:数学cos()返回NaN

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //Create a variable.
    //Square root of a negative number.
    //The result is not a number (NaN)
    double a = Math.sqrt(-5);
    //Implement infinity with Double
    double infinity = Double.POSITIVE_INFINITY;
    //Print the cosine value
    System.out.println(Math.cos(a));  // NaN
    System.out.println(Math.cos(infinity));  // NaN
  }
}

Here, we create a variable named a.

  • Math.cos(a) -Returns NaN because a negative number (-5) is not a number

Double.POSITIVE_INFINITY is a field of the Double class. It is used to implement infinity in Java.

Note: We have usedJava Math sqrt()Method to calculate the square root of a number.

Recommended Tutorials

Java Math Mathematical Methods