• switch语句会匹配多个表达式。
  • 如果想匹配一个,需要加关键字,case 一旦匹配上某一个,则结束匹配。 ```cpp

    include

int main() { char c; c = getchar();

  1. switch (c) //参数只能是整型变量
  2. {
  3. case '1':
  4. printf("OK\n");
  5. break;//switch遇到break就中断了
  6. case '2':
  7. printf("not OK\n");
  8. break;
  9. default://如果上面的条件都不满足,那么执行default
  10. printf("are u ok?\n");
  11. }
  12. return 0;

}

  1. ```cpp
  2. #include <stdio.h>
  3. #include <stdbool.h>
  4. #define ADD '+'
  5. #define SUB '-'
  6. #define MULTIPLY '*'
  7. #define DIVIDE '/'
  8. #define REM '%'
  9. int main() {
  10. int left;
  11. int right;
  12. while (true) {
  13. char operator;
  14. printf("Please input an expression: \n");
  15. scanf("%d %c %d", &left, &operator, &right);
  16. int result;
  17. switch (operator) {
  18. case ADD:
  19. result = left + right;
  20. break;
  21. case SUB:
  22. result = left - right;
  23. break;
  24. case MULTIPLY:
  25. result = left * right;
  26. break;
  27. case DIVIDE:
  28. result = left / right;
  29. break;
  30. case REM:
  31. result = left % right;
  32. break;
  33. default:
  34. printf("Unsupported operation: %c\n", operator);
  35. return 1;
  36. }
  37. printf("Result: %d\n", result);
  38. }
  39. return 0;
  40. }