Learn-c-by-examples-compare-three-integers-in-c

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

Cの3つの整数を比較する

3つの整数変数の比較は、簡単に作成できる最も単純なプログラムの1つです。 このプログラムでは、 `+ scanf()+`関数を使用してユーザーから入力を受け取るか、プログラム自体で静的に定義できます。

あなたにとってもシンプルなプログラムになると期待しています。 1つの値を残りの2つと比較して結果を確認すると、すべての変数に同じプロセスが適用されます。 このプログラムでは、すべての値が異なる(一意の)必要があります。

アルゴリズム

最初に3つの整数を比較するためのステップバイステップの手順を見てみましょう-

START
   Step 1 → Take two integer variables, say A, B& C
   Step 2 → Assign values to variables
   Step 3 → If A is greater than B & C, Display A is largest value
   Step 4 → If B is greater than A & C, Display B is largest value
   Step 5 → If C is greater than A & B, Display A is largest value
   Step 6 → Otherwise, Display A, B & C are not unique values
STOP

流れ図

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

3つの比較フローチャート

この図は、3つの「+ if-else-if 」と1つの「 else +」比較文を示しています。

疑似コード

このアルゴリズムの擬似コードを見てみましょう-

procedure compare(A, B, C)

   IF A is greater than B AND A is greater than C
      DISPLAY "A is the largest."
   ELSE IF B is greater than A AND A is greater than C
      DISPLAY "B is the largest."
   ELSE IF C is greater than A AND A is greater than B
      DISPLAY "C is the largest."
   ELSE
      DISPLAY "Values not unique."
   END IF

end procedure

実装

今、私たちはプログラムの実際の実装が表示されます-

#include <stdio.h>

int main() {
   int a, b, c;

   a = 11;
   b = 22;
   c = 33;

   if ( a > b && a > c )
      printf("%d is the largest.", a);
   else if ( b > a && b > c )
      printf("%d is the largest.", b);
   else if ( c > a && c > b )
      printf("%d is the largest.", c);
   else
      printf("Values are not unique");

   return 0;
}

出力

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

33 is the largest.