C语言,用函数实现计算器的加,减,乘,除
时间: 2023-10-01 16:07:31 浏览: 229
可以参考下面的代码实现:
```c
#include <stdio.h>
// 加法函数
int add(int a, int b) {
return a + b;
}
// 减法函数
int sub(int a, int b) {
return a - b;
}
// 乘法函数
int mul(int a, int b) {
return a * b;
}
// 除法函数
float div(int a, int b) {
return (float) a / b;
}
int main() {
int a, b, choice;
printf("请输入两个数字: ");
scanf("%d %d", &a, &b);
printf("请选择要进行的操作: \n");
printf("1. 加法\n");
printf("2. 减法\n");
printf("3. 乘法\n");
printf("4. 除法\n");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("%d + %d = %d\n", a, b, add(a, b));
break;
case 2:
printf("%d - %d = %d\n", a, b, sub(a, b));
break;
case 3:
printf("%d * %d = %d\n", a, b, mul(a, b));
break;
case 4:
if (b == 0) {
printf("除数不能为0!\n");
} else {
printf("%d / %d = %.2f\n", a, b, div(a, b));
}
break;
default:
printf("无效的选项!\n");
break;
}
return 0;
}
```
运行程序后,输入两个数字和要进行的操作,即可得到计算结果。注意在除法函数中需要判断除数是否为0。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)