JavaScript 计算平方根的程序

要理解此示例,您应了解以下 JavaScript 编程 主题


要在 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

另请阅读

在结束之前,让我们通过以下挑战来检验您对 JavaScript 程序查找平方根的知识!您能解决以下挑战吗?

挑战

编写一个函数来查找数字的平方根。

  • 返回给定数字 num 的平方根。
  • 例如,如果 num = 25,则预期输出为 5
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战