c语言中的切换大小写问题

  • 本文关键字:大小写 问题 语言 c
  • 更新时间 :
  • 英文 :


这是我第一次使用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完成后。

最新更新