C 语言中的平方根程序



求一个数的平方根的过程可以分成两个步骤。第一步是求出整数部分,第二步是求出小数部分。

算法

我们在下面推导出一个求平方根的算法 −

START
   Step 1 → Define value n 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

伪代码

这个算法的伪代码可以推导如下 −

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

实现

这个算法的实现如下 −

#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;
}

输出

程序的输出应该是 −

Square root of 24 = 4.898980
mathematical_programs_in_c.htm
广告