[英]Switch case problems in c language
这是我第一次使用 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");
}
一些消息来源甚至主张在最后一个案例结束时设置一个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
完成后停止测试 switch 用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.