如何在JavaScript中求一个数的立方根?


在本文中,我们将讨论如何使用JavaScript以及合适的示例来求一个数的立方根。

在JavaScript中,可以使用Math对象进行各种运算。`Math.cbrt()`、`Math.pow()`方法尤其用于求一个数的立方根,我们也可以使用`**`运算符来实现。它以一个数字作为参数,并返回其立方根。

在JavaScript中,求一个数的立方根有三种方法。第一种方法是使用`cbrt()`方法,第二种方法是使用`pow()`方法,第三种方法是使用`**`运算符。

语法

下面显示了`cbrt()`方法的语法。

Math.cbrt(value)

这里,`value`作为输入,它应该是一个数字。它返回`value`的立方根。

示例1

以下是一个使用`cbrt()`方法求一个数的立方根的示例程序。

<!DOCTYPE html>
<html>
<head>
   <title>To find the cube root of a number in JavaScript</title>
</head>
<body style="text-align : center">
   <h3>To find the cube root of a number in JavaScript</h3>
   <p id='cbrt'></p>
   <script>
      let a = Math.cbrt(36, 1/3);
      let b = Math.cbrt(125,1/3);
      let c = Math.cbrt(-36.1/3);
      let d = Math.cbrt(-125,1/3);
      document.getElementById('cbrt').innerHTML = `The cube root value for 36 is ${a} ${'<br/>'} The cube root value for 125 is ${b} ${'<br/>'} The cube root value for -36 is ${c} ${'<br/>'} The cube root value for -125 is ${d} ${'<br/>'}`;
   </script>
</body>
</html>

执行上述代码后,将生成以下输出。

示例2

以下是一个使用`pow()`方法求一个数的立方根的示例程序。

<!DOCTYPE html>
<html>
<head>
   <title>To find the cube root of a number in JavaScript</title>
</head>
<body style="text-align : center">
   <h3>To find the cube root of a number in JavaScript</h3>
   <p id='cbrt'></p>
   <script>
      let a = Math.pow(27,1/3);
      let b = Math.pow(125,1/3);
      let c = Math.pow(64,1/3);
      let d = Math.pow(39,1/3);
      document.getElementById('cbrt').innerHTML = `The cube root value for 27 is ${a} ${'<br/>'} The cube root value for 125 is ${b} ${'<br/>'} The cube root value for 64 is ${c} ${'<br/>'} The cube root value for 39 is ${d} ${'<br/>'}`;
   </script>
</body>
</html>

执行上述代码后,将生成以下输出。

示例3

以下是一个使用`**`运算符求一个数的立方根的示例程序。

<!DOCTYPE html>
<html>
<head>
   <title>To find the cube root of a number in JavaScript</title>
</head>
<body style="text-align : center">
   <h3>To find the cube root of a number in JavaScript</h3>
   <p id='cbrt'></p>
   <script>
      let a = 27 ** (1/3);
      let b = 125 ** (1/3);
      let c = 36 ** (1/3);
      let d = 75 ** (1/3);
      document.getElementById('cbrt').innerHTML = `The cube root value for 27 is ${a} ${'<br/>'} The cube root value for 125 is ${b} ${'<br/>'} The cube root value for 36 is ${c} ${'<br/>'} The cube root value for 75 is ${d} ${'<br/>'}`;
   </script>
</body>
</html>

执行上述代码后,将生成以下输出。

更新于:2022年12月8日

3K+ 浏览量

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.