这是我第一次使用switch. case,我需要做一个程序,用户选择一个操作符,选择2个数字,然后显示结果,但是当我这样做的时候,它适用于所有选项,我不知道为什么
下面是我的代码:
#include <stdio.h>
int main() {
char op;
double first, second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
switch (op) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
default:
printf("Error! operator is not correct");
}
return 0;
}
switch
语句中的case
标签就是标签。它们不会将语句体细分为更小的块;相反,它们只是标记控制可以分支到的不同位置(实际上是不同的语句)。你所描述的行为是自然的结果。如果你不做任何事情来阻止它,在一个标签分支到switch
体的控制流将不间断地通过其他标签继续。
要在任何时候跳出switch
,请使用break
语句。通常在每个case
标签和default
标签(如果有的话)之前放置一个break
。例子:
switch (op) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
default:
printf("Error! operator is not correct");
}
一些来源甚至主张在最后一个case的末尾加上一个break
,尽管这没有任何功能效果。
switch (c) {
case 'a':
// fall through
case 'e':
// fall through
case 'i':
// fall through
case 'o':
// fall through
case 'u':
handle_vowel(c);
break;
default:
handle_consonant(c);
}
您在所有案例结束时都缺少break
您在每种情况下都缺少语句后的break
。下面是C和c++中switch语句的主要语法,但它也可以应用于其他编程语言。
switch(expression) {
case value1:
statement_1;
break;
case value2:
statement_2;
break;
...
case value_n:
statement_n;
break;
default:
default statement;
}
break
关键字告诉程序停止测试切换情况下statement
完成后。