工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> C言語

C スイッチステートメント

C switch ステートメント

このチュートリアルでは、例を使用して C プログラミングで switch ステートメントを作成する方法を学習します。

switch ステートメントを使用すると、多くの選択肢の中から 1 つのコード ブロックを実行できます。

if...else..if でも同じことができます はしご。ただし、 switch の構文は ステートメントは読み書きがはるかに簡単です。


switch...case の構文

switch (expression)
​{
    case constant1:
      // statements
      break;

    case constant2:
      // statements
      break;
    .
    .
    .
    default:
      // default statements
}

switch ステートメントはどのように機能しますか?

一度評価され、各 case の値と比較されます

注:


switch ステートメントのフローチャート

<図>

例:簡単な電卓

// Program to create a simple calculator
#include <stdio.h>

int main() {
    char operation;
    double n1, n2;

    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operation);
    printf("Enter two operands: ");
    scanf("%lf %lf",&n1, &n2);

    switch(operation)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
            break;

        case '-':
            printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
            break;

        case '*':
            printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
            break;

        case '/':
            printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
            break;

        // operator doesn't match any case constant +, -, *, /
        default:
            printf("Error! operator is not correct");
    }

    return 0;
}

出力

Enter an operator (+, -, *, /): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1

- ユーザーが入力した演算子は operation に格納されます 変数。そして、2 つのオペランド 32.5 および 12.4 変数 n1 に格納されます と n2

作戦以来 - です 、プログラムの制御は

にジャンプします
printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

最後に、break ステートメントは switch を終了します。


C言語

  1. スイッチ付き回路
  2. 整流ダイオード
  3. スイッチタイプ
  4. 「バウンス」に連絡する
  5. マルチメータ
  6. C# switch ステートメント
  7. C# break ステートメント
  8. C# 継続ステートメント
  9. C++ break ステートメント
  10. C++ Switch Case ステートメントと EXAMPLE
  11. C - 基本構文