在 JavaScript 中不使用 Math.sqrt() 求数字的平方根

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/21 23:40:17

我们需要编写一个 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

相关文章


有用资源