c语言编程做一个计算器
时间: 2023-10-08 21:09:45 浏览: 89
好的,下面是一个简单的示例代码,可以实现基本的加减乘除四则运算:
```c
#include <stdio.h>
int main() {
float num1, num2, result; // 定义操作数和结果
char op; // 定义运算符
printf("请输入两个操作数:");
scanf("%f %f", &num1, &num2); // 读取操作数
printf("请输入运算符:");
scanf(" %c", &op); // 注意运算符前面需要加一个空格,避免读取上一行的换行符
switch (op) {
case '+': // 加法
result = num1 + num2;
break;
case '-': // 减法
result = num1 - num2;
break;
case '*': // 乘法
result = num1 * num2;
break;
case '/': // 除法
if (num2 == 0) {
printf("除数不能为0!\n");
return 1; // 返回错误码
}
result = num1 / num2;
break;
default: // 非法运算符
printf("非法运算符!\n");
return 1; // 返回错误码
}
printf("运算结果为:%.2f\n", result);
return 0;
}
```
在编译运行时,需要注意一些细节:
- 代码中使用了浮点数类型 `float`,需要在读取操作数时使用 `%f` 格式符。
- 读取运算符时,需要在 `%c` 前面加一个空格,避免读取上一行的换行符。
- 除法运算时需要判断除数是否为0,避免程序崩溃。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)