用c语言用switch语句模拟简单的计算器,进行整数的加减乘除四则运算,输入一个表达式,输出表达式的计算结果。例如,输入3*5,输出3*5=15,特殊处理除法,商保留两位小数
时间: 2023-05-25 19:03:05 浏览: 85
```c
#include <stdio.h>
int main() {
char operator;
int operand1, operand2;
printf("请输入表达式(如3+5):\n");
scanf("%d%c%d", &operand1, &operator, &operand2);
switch (operator) {
case '+':
printf("%d+%d=%d\n", operand1, operand2, operand1 + operand2);
break;
case '-':
printf("%d-%d=%d\n", operand1, operand2, operand1 - operand2);
break;
case '*':
printf("%d*%d=%d\n", operand1, operand2, operand1 * operand2);
break;
case '/':
if (operand2 == 0) {
printf("错误:除数不能为0\n");
break;
}
printf("%d/%d=%.2f\n", operand1, operand2, (float)operand1 / operand2);
break;
default:
printf("错误:不支持的运算符\n");
break;
}
return 0;
}
```
需注意以下几点:
1. 输入格式为两个整数和一个字符,中间用空格或其他不产生歧义的字符(如+、-、*、/)隔开。
2. 除法计算结果需要强制转换为浮点数,保留两位小数(使用%.2f格式化输出)。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)