Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tìm căn bậc ba của số trong JavaScript

Sử dụng Math object trong JavaScript có thể thực hiện mọi phép toán. Math.cbrt() là phương thức chuyên dụng để tìm căn bậc ba của một số. Nhận một số làm tham số và trả về căn bậc ba.

Cú pháp

Math.cbrt(64);

Ví dụ 1: Số dương

<html> <body> <script>    document.write(Math.cbrt(64));    document.write("</br>");    document.write(Math.cbrt(27));    document.write("</br>");    document.write(Math.cbrt(0)); </script> </body> </html>

Kết quả

4 3 0

Ví dụ 2: Số âm và đặc biệt

Phương thức này cũng nhận giá trị âm.

<html> <body> <script>    document.write(Math.cbrt(-64));    document.write("</br>");    document.write(Math.cbrt(-27));    document.write("</br>");    document.write(Math.cbrt(0));    document.write("</br>");    document.write(Math.cbrt(Infinity)); </script> </body> </html>

Kết quả

-4 -3 0 Infinity

Lưu ý: Khác với Math.sqrt() (chỉ cho số ≥ 0), Math.cbrt() hoạt động với mọi số thực bao gồm số âm. Math.cbrt(-8) = -2 vì (-2)³ = -8.