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

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

Cのキューブルートプログラム

与えられた数が偶数または奇数であることを見つけることは、古典的なCプログラムです。 Cでの条件文「+ if-else +」の使用方法を学習します。

アルゴリズム

このプログラムのアルゴリズムは非常に簡単です-

START
   Step 1 → Take integer variable A
   Step 2 → Assign value to the variable
   Step 3 → Perform A modulo 2 and check result if output is 0
   Step 4 → If true print A is even
   Step 5 → If false print A is odd
STOP

流れ図

以下に示すように、このプログラムのフロー図を描くことができます-

FlowDiagram Even Odd

疑似コード

procedure even_odd()

   IF (number modulo 2) equals to 0
      PRINT number is even
   ELSE
      PRINT number is odd
   END IF

end procedure

実装

このアルゴリズムの実装は以下のとおりです-

#include <stdio.h>

double cubeRoot(double n) {
   double i, precision = 0.000001;

   for(i = 1; (i*i*i) <= n; ++i);        //Integer part

   for(--i; (i*i*i) < n; i += precision); //Fractional part

   return i;
}

int main() {
   int n = 125;

   printf("Cube root of %d = %lf", n, cubeRoot(n));

   return 0;
}

出力

プログラムの出力は次のようになります-

Cube root of 125 = 5.000000