如何在 JavaScript 中獲取數字的平方根?
在本教程中,我們將學習如何透過兩種方式在 JavaScript 中獲取數字的平方根。
在 JavaScript 中,可以透過兩種方式找到數字的平方根:
- 使用 Math.sqrt() 方法
- 建立自定義函式
數字的平方根是一個因子,它自身相乘等於原數字。例如,10 是 100 的平方根,因為 10 自身相乘 (10*10) 的結果是 100。
使用 Math.sqrt() 方法
在 JavaScript 中,Math.sqrt() 方法用於查詢數字的平方根。它接受一個變數作為引數,如果變數是正數,則返回平方根值。否則,如果變數是負數或非數值,則返回 NaN,表示“非數字”。
使用者可以按照以下語法使用 Math.sqrt() 方法查詢數字的平方根。
語法
Math.sqrt( number );
引數
number − 接受任何需要求平方根的數字變數。
返回型別
給定正數的平方根。
如果引數是負數或非數值,則返回NaN。
示例 1
在下面的示例中,我們使用了 Math.sqrt() 方法來查詢數字的平方根。我們使用了不同的值來觀察 Math.sqrt() 方法的輸出。
<html> <body> <h4> Get the square root of a number using <i>Math.sqrt() </i> method </h4> <div id="root"> </div> <script> let positive_number = 4; let negative_number = -4; let root = document.getElementById('root'); root.innerHTML = "The square root of " + positive_number + " is: " + Math.sqrt(positive_number) + "<br>"; root.innerHTML += "The square root of " + negative_number + " is:" + Math.sqrt(negative_number) + "<br>"; </script> </body> </html>
在上面的輸出中,使用者可以看到 Math.sqrt() 方法對於正整數返回所需的平方根值,對於負數和非數值,它返回 NaN。
建立自定義方法
也可以不使用 Math.sqrt() 方法來計算數字的平方根,這種方法需要使用迭代來計算平方根值。
語法
function square_root(num) { //checking if number is negative or non-numeric if (num < 0 || isNaN(num)) { return NaN } //starting the calculation from half of the number let square_root = num / 2 let temp = 0 // Iterating while square_root is not equal to temp while (square_root != temp) { temp = square_root // smalling the square_root value to find square root square_root = (num / square_root + square_root) / 2 } return square_root }
演算法
步驟 1 − 宣告一個函式,並在函式中接受一個數字作為引數。
步驟 2 − 檢查數字是否為負數或非數值,並返回 NaN。
步驟 3 − 將 square_root 變數設定為給定數字的一半,並宣告一個值為 0 的 temp 變數。
步驟 4 − 當 temp 不等於 square_root 值時迭代。
步驟 4.1 − 將 square_root 值儲存在 temp 中。
步驟 4.2 − 將數字除以當前的 square_root 值,並將結果與當前的 square_root 值相加。
步驟 5 − 返回 square_root 值。
示例
在下面的示例中,我們不使用 Math.sqrt() 方法來計算數字的平方根。我們使用了不同的值來觀察輸出。
<html> <body> <h4> Get the square root of a number without using <i> custom </i> method. </h4> <div id = "root"> </div> <script> function square_root(num) { //checking if number is negative or non-numeric if (num < 0 || isNaN(num)) { return NaN } //starting the calculation from half of the number let square_root = num / 2 let temp = 0 // Iterating while square_root is not equal to temp while (square_root != temp) { temp = square_root // smalling the square_root value to find the square root square_root = (num / square_root + square_root) / 2 } return square_root } let positive_number = 121; let negative_number = -6; let root = document.getElementById('root'); root.innerHTML = "The square root of " + positive_number + " is: " + square_root(positive_number) + "<br>";root.innerHTML += "The square root of " + negative_number + " is: " +square_root(negative_number) + "<br>"; </script> </body> </html>
在上面的輸出中,使用者可以看到 square_root 方法對於正整數返回所需的平方根值,對於負數和非數值也是如此。我們學習瞭如何使用和不使用 Math.sqrt() 方法在 JavaScript 中獲取數字的平方根值。第一種方法是獲取平方根值的標準方法。第二種方法是更可控的方法,如果您想做的不僅僅是獲取平方根值,請選擇第二種方法。建議使用 Math.sqrt() 方法,因為它是一個 JavaScript 內建方法。