要计算数字的结尾根,请使用Math.abs()方法。在这里,我们也使用Match.pow方法。您可以尝试运行以下代码来计算JavaScript中数字的平方根-
<html>
<head>
<title>Calculate root</title>
</head>
<body>
<script>
function displayRoot(x, num) {
val = num % 2;
if((val == 1) || x < 0)
x = -x;
var a, num;
a = Math.pow(x, 1 / num);
num = Math.pow(a, num);
if(Math.abs(x - num) < 1 && (x > 0 === num > 0))
return val ? -a : a;
}
document.write(displayRoot(36, 2));
document.write("<br>"+displayRoot(49, 2));
document.write("<br>"+displayRoot(36, -2));
document.write("<br>"+displayRoot(216, -2));
</script>
-+
</body>
</html>