如何在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>
執行上述程式碼後,將生成以下輸出。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP