JavaScript Math cos()

cos() 方法计算指定角度的三角余弦值并返回它。

示例

// cosine of the angle 1
let value = Math.cos(1);
console.log(value);

// Output: 0.5403023058681398

cos() 语法

Math.cos() 方法的语法是:

Math.cos(angle)

在这里,cos() 是一个静态方法。因此,我们通过类名 Math 来访问该方法。


cos() 参数

cos() 方法接受一个参数:

  • angle - 以弧度为单位,计算其余弦值。

cos() 返回值

cos() 方法返回:

  • 给定 angle (以弧度为单位)的余弦值。
  • 对于非数字参数,返回 NaN(非数字)。

示例 1:JavaScript Math.cos()

// cosine of 5 radians let value1 = Math.cos(5);
console.log(value1);
// negative radians are allowed let value2 = Math.cos(-2);
console.log(value2); // Output: // 0.28366218546322625 // -0.4161468365471424

在上面的例子中:

  • Math.cos(5) - 计算角度 5 的余弦值。
  • Math.cos(-2) - 计算角度 -2 的余弦值。

示例 2:Math.cos() 与 Math 常量

// math constants as arguments let value3 = Math.cos(Math.PI);
console.log(value3); // Output: -1

在上面的示例中,我们使用 cos() 方法计算了数学常量 PI 的余弦值。


示例 3:Math.cos() 与非数字参数

let string = "Darth Vader";

// cos() with string as argument let value = Math.cos(string);
console.log(value); // Output: // NaN

在上面的示例中,我们尝试计算字符串 "Darth Vader" 的余弦值,结果为 NaN


示例 4:Math.cos() 与 Infinity

// infinity as argument let value1 = Math.cos(Infinity);
console.log(value1);
// negative infinity as argument let value2 = Math.cos(-Infinity);
console.log(value2); // Output: // NaN // NaN

cos() 方法不将无穷大视为数字,因此使用该参数时方法返回 NaN

此外,无穷角度的余弦值是不确定的,无法用数字定义。


推荐阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战