switch语句实现简单计算器的代码
时间: 2023-12-24 15:24:32 浏览: 62
下面是使用switch语句实现简单计算器的代码,它能够接受用户输入的两个数字和一个运算符,并根据运算符进行相应的运算,然后输出结果。代码中使用了switch语句来判断运算符,根据不同的运算符执行相应的计算操作。
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
float a, b, result;
char operator;
printf("Enter two numbers: ");
scanf("%f %f", &a, &b);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
switch(operator) {
case '+':
result = a + b;
printf("%.2f + %.2f = %.2f", a, b, result);
break;
case '-':
result = a - b; printf("%.2f - %.2f = %.2f", a, b, result);
break;
case '*':
result = a * b;
printf("%.2f * %.2f = %.2f", a, b, result);
break;
case '/':
if (b == 0) {
printf("Error: division by zero");
} else {
result = a / b;
printf("%.2f / %.2f = %.2f", a, b, result);
}
break;
default:
printf("Error: invalid operator");
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)