Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 求平方根的程序

求平方根的 JavaScript 程序

在这个例子中,您将学习编写一个程序来在 JavaScript 中找到一个数字的平方根。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 变量和常量 JavaScript Math sqrt()
要在 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
如果在 Math.sqrt() 方法中传递了 0 或正数,则返回该数字的平方根。 如果传递负数,则返回 NaN 如果传递了字符串,则返回 NaN
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4