用switch结构设计有两个操作数的数学运算。 C语言
时间: 2023-06-14 22:06:48 浏览: 56
下面是一个示例程序,可以通过switch结构实现加减乘除四种数学运算:
```c
#include <stdio.h>
int main() {
char operator;
float operand1, operand2, result;
printf("请输入两个操作数:\n");
scanf("%f %f", &operand1, &operand2);
printf("请输入运算符(+、-、*、/):\n");
scanf(" %c", &operator);
switch (operator) {
case '+':
result = operand1 + operand2;
printf("%.2f + %.2f = %.2f\n", operand1, operand2, result);
break;
case '-':
result = operand1 - operand2;
printf("%.2f - %.2f = %.2f\n", operand1, operand2, result);
break;
case '*':
result = operand1 * operand2;
printf("%.2f * %.2f = %.2f\n", operand1, operand2, result);
break;
case '/':
if (operand2 == 0) {
printf("错误:除数不能为0!\n");
} else {
result = operand1 / operand2;
printf("%.2f / %.2f = %.2f\n", operand1, operand2, result);
}
break;
default:
printf("错误:未知的运算符!\n");
break;
}
return 0;
}
```
用户输入两个操作数和一个运算符后,程序就可以根据运算符进行相应的数学运算,并输出结果。注意要对除数为0的情况进行特判。