定义两个double型变量a,b,一个字符型变量Q,依次输入第一个运算数、运算符(+,-,*,/)、第二个运算数,利用switch语句实现数字的加减乘除四则运算,然后输出结果,保留两位小数输出。注意:除数不能为0。用c语言编写程序
时间: 2024-10-22 10:12:05 浏览: 87
在C语言中,你可以创建一个简单的程序来实现这个需求。下面是一个示例程序:
```c
#include <stdio.h>
#include <math.h> // 引入数学库,用于浮点数除法
void calculate(double a, double b, char op) {
switch(op) {
case '+':
printf("Result: %.2f\n", a + b);
break;
case '-':
printf("Result: %.2f\n", a - b);
break;
case '*':
printf("Result: %.2f\n", a * b);
break;
case '/':
if (b != 0) { // 检查除数是否为0
printf("Result: %.2f\n", a / b);
} else {
printf("Error! Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator!\n");
break;
}
}
int main() {
double a, b;
char Q;
printf("Enter the first number: ");
scanf("%lf", &a);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &Q); // 注意这里需要额外的空间读取空格
getchar(); // 清理输入缓冲区,避免后续字符影响
printf("Enter the second number: ");
scanf("%lf", &b);
calculate(a, b, Q); // 调用函数进行计算并输出结果
return 0;
}
```
在这个程序中,我们首先定义了一个`calculate`函数,它接受两个双精度数和一个字符作为参数,并使用`switch`语句判断操作符来执行相应的运算。注意检查了除数是否为零的情况。
在`main`函数中,用户被提示分别输入两个数值和运算符,然后调用`calculate`函数处理输入并显示结果。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)