在JavaScript中不使用Math.sqrt()查找数字的平方根
我们需要编写一个以正整数作为唯一参数的JavaScript函数。该函数应找到并返回作为输入提供的数字的平方根。
示例
以下是代码-
const squareRoot = (num, precision = 0) => {
if (num <= 0) {
return 0;
};
let res = 1;
const deviation = 1 / (10 ** precision);
while (Math.abs(num - (res ** 2)) > deviation) {
res -= ((res ** 2) - num) / (2 * res);
};
return Math.round(res * (10 ** precision)) / (10 ** precision);
};
console.log(squareRoot(16));
console.log(squareRoot(161, 3));
console.log(squareRoot(1611, 4));输出结果以下是控制台上的输出-
4 12.689 40.1373
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短