在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 婆婆高寿祝福语大全简短