用c语言设计一个加减乘除的计算器
时间: 2023-10-21 07:05:45 浏览: 58
好的,以下是一个简单的四则运算计算器的 C 语言代码:
```c
#include <stdio.h>
int main() {
char operator;
float num1, num2, result;
printf("请输入运算符 (+, -, *, /): ");
scanf("%c", &operator);
printf("请输入两个数字: ");
scanf("%f %f", &num1, &num2);
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
printf("除数不能为 0\n");
return 1;
} else {
result = num1 / num2;
}
break;
default:
printf("无效的运算符\n");
return 1;
}
printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);
return 0;
}
```
运行程序后,输入运算符和两个数字,就可以得到结果。例如:
```
请输入运算符 (+, -, *, /): *
请输入两个数字: 2 3
2.00 * 3.00 = 6.00
```
注意,这个计算器没有考虑输入错误的情况,比如输入非数字的字符。在实际应用中,需要对程序进行更加完善的错误处理。
相关推荐
![](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)
![](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)