要在 JavaScript 中查找数字的平方根,您可以使用内置的 Math.sqrt()
方法。其语法是
Math.sqrt(number);
在这里,Math.sqrt()
方法接受一个数字并返回其平方根。
示例:数字的平方根
// take the input from the user
const number = prompt('Enter the number: ');
const result = Math.sqrt(number);
console.log(`The square root of ${number} is ${result}`);
输出
Enter the number: 9 The square root of 9 is 3
示例 2:不同数据类型的平方根
const number1 = 2.25;
const number2 = -4;
const number3 = 'hello';
const result1 = Math.sqrt(number1);
const result2 = Math.sqrt(number2);
const result3 = Math.sqrt(number3);
console.log(`The square root of ${number1} is ${result1}`);
console.log(`The square root of ${number2} is ${result2}`);
console.log(`The square root of ${number3} is ${result3}`);
输出
The square root of 2.25 is 1.5 The square root of -4 is NaN The square root of hello is NaN
- 如果将 0 或正数传递给
Math.sqrt()
方法,则会返回该数字的平方根。 - 如果传递负数,则返回
NaN
。 - 如果传递字符串,则返回
NaN
。
另请阅读