Square root

优质
小牛编辑
126浏览
2023-12-01

找到数字的平方根的过程可以分为两个步骤。 一步是找到整数部分,第二步是分数部分。

算法 (Algorithm)

我们在这里推导出一种寻找平方根的算法 -

START
   Step 1 → Define value <b>n</b> to find square root of
   Step 2 → Define variable i and set it to 1 (For integer part)
   Step 3 → Define variable p and set it to 0.00001 (For fraction part)
   Step 4 → While i*i is less than n, increment i
   Step 5 → Step 4 should produce the integer part so far
   Step 6 → While i*i is less than n, add p to i
   Step 7 → Now i has the square root value of n
STOP

伪代码 (Pseudocode)

该算法的伪代码可以推导如下 -

procedure square_root( n )
   SET precision TO 0.00001
   FOR i = 1 TO i*i < n DO
      i = i + 1
   END FOR
   FOR i = i - 1 TO i*i < n DO
      i = i + precision
   END FOR
   DISPLAY i AS square root
end procedure

实现 (Implementation)

该算法的实现如下 -

#include <stdio.h>
double squareRoot(double n) {
   double i, precision = 0.00001;
   for(i = 1; i*i <=n; ++i);           //Integer part
   for(--i; i*i < n; i += precision);  //Fractional part
   return i;
}
int main() {
   int n = 24;
   printf("Square root of %d = %lf", n, squareRoot(n));
   return 0;
}

输出 (Output)

该方案的产出应该是 -

Square root of 24 = 4.898980