Learn-c-by-examples-square-root-program-in-c

提供:Dev Guides
移動先:案内検索

Cの平方根プログラム

数値の平方根を見つけるプロセスは、2つのステップに分けることができます。 1つのステップは整数部を見つけることで、2番目のステップは小数部を見つけることです。

アルゴリズム

ここで平方根を見つけるためのアルゴリズムを導出します-

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