sqrt()
方法计算指定数字的平方根并返回它。
示例
// square root of 4
let number = Math.sqrt(4);
console.log(number);
// Output: 2
sqrt() 语法
Math.sqrt()
方法的语法是:
Math.sqrt(number)
这里,sqrt()
是一个静态方法。因此,我们通过类名 Math
来访问该方法。
sqrt() 参数
sqrt()
方法接受一个参数:
number
- 需要计算平方根的值
sqrt() 返回值
sqrt()
方法返回:
- 给定正整数或小数
number
的平方根 - 如果参数是非数字或负数,则返回 NaN (Not a Number)。
示例 1:JavaScript Math.sqrt()
// sqrt() with integer number
let number1 = Math.sqrt(16);
console.log(number1);
// sqrt() with a floating number
let number2 = Math.sqrt(144.64);
console.log(number2);
// Output:
// 4
// 12.026637102698325
在这里,我们使用 Math.sqrt()
方法计算整数值 16 和小数 144.64 的平方根。
示例 2:带负数的参数的 sqrt()
// sqrt() with negative number
let number = Math.sqrt(-324);
console.log(number);
// Output: NaN
数学上,任何负数的平方根都是虚数。这就是为什么 sqrt()
方法返回 NaN 作为输出。
示例 3:带无穷大值的 sqrt()
// sqrt() with positive infinity
let number1 = Math.sqrt(Infinity);
console.log(number1);
// Output: Infinity
// sqrt() with negative infinity
let number2 = Math.sqrt(-Infinity);
console.log(number2);
// Output: NaN
示例 4:带数字字符串的 sqrt()
// cbrt() with a decimal number
let number1 = Math.cbrt("81");
console.log(number1);
// Output: 4.326748710922225
在上面的示例中,Math.sqrt()
方法将数字字符串 "81"
转换为数字,然后计算其平方根。
示例 5:带非数字参数的 sqrt()
let string = "Harry";
// sqrt() with string as argument
let number = Math.sqrt(string);
console.log(number);
// Output: NaN
在上面的示例中,我们尝试计算字符串 "Harry"
的平方根。这就是为什么我们得到 NaN 作为输出。
另请阅读