用C语言完成一个简单计算器
时间: 2023-12-17 07:45:27 浏览: 77
以下是用C语言编写的简单计算器程序:
```
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
printf("请输入要进行的计算(例如:2 + 3):");
scanf("%f %c %f", &num1, &operator, &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 0;
}
result = num1 / num2;
break;
default:
printf("输入的运算符不合法\n");
return 0;
}
printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);
return 0;
}
```
程序首先提示用户输入要进行的计算,例如:2 + 3。然后使用scanf函数读取用户输入的数字和运算符。接着使用switch语句对不同的运算符进行判断,并执行相应的计算操作。如果用户输入的是除法运算符,并且除数为0,则提示用户除数不能为0。最后输出计算结果。注意,使用%.2f格式化输出浮点数,保留小数点后两位。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)