c编写一个四则运算计算器程序,从键盘输入任意两个数和一个运算符(+、-、*、/),计算其运算的结果并输出,要求分别使用if和switch语句编程
时间: 2024-02-22 08:00:46 浏览: 131
使用if语句实现:
```c
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
printf("请输入两个数和运算符(+、-、*、/):\n");
scanf("%f %f %c", &num1, &num2, &operator);
if (operator == '+') {
result = num1 + num2;
} else if (operator == '-') {
result = num1 - num2;
} else if (operator == '*') {
result = num1 * num2;
} else if (operator == '/') {
if (num2 == 0) {
printf("除数不能为0!\n");
return 0;
}
result = num1 / num2;
} else {
printf("运算符输入错误!\n");
return 0;
}
printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);
return 0;
}
```
使用switch语句实现:
```c
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
printf("请输入两个数和运算符(+、-、*、/):\n");
scanf("%f %f %c", &num1, &num2, &operator);
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;
}
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)