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 の値と比較されます
- 一致する場合は、一致するラベルの後の対応するステートメントが実行されます。たとえば、式の値が constant2 と等しい場合 、
case constant2:
の後のステートメントbreak
まで実行されます - 一致がない場合、デフォルトのステートメントが実行されます。
注:
break
を使用しない場合 一致するラベルの後のすべてのステートメントも実行されます。default
switch
内の句 ステートメントはオプションです。
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言語