在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 团队虎年祝福语简短霸气