📜  查找平方根的JavaScript程序

📅  最后修改于: 2020-09-27 05:31:30             🧑  作者: Mango

在此示例中,您将学习编写程序以在JavaScript中查找数字的平方根。

要在JavaScript中找到数字的平方根,可以使用内置的Math.sqrt()方法。其语法为:

Math.sqrt(number);

在此, Math.sqrt()方法采用一个数字并返回其平方根。


示例:数字的平方根
// take the input from the user
let number = prompt('Enter the number: ');

let 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:不同数据类型的平方根
let number1 = 2.25;
let number2 = -4;
let number3 = 'hello';

let result1 = Math.sqrt(number1);
let result2 = Math.sqrt(number2);
let 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
  • 如果在Math.sqrt()方法中传递了数字,则将返回该数字的平方根。
  • 如果传递负数,则返回NaN
  • 如果传递了字符串 ,则返回NaN