帮我写一个计算器的c语言代码
时间: 2024-11-29 15:34:50 浏览: 14
我可以帮你提供一个简单的控制台版的四则运算计算器的C语言代码示例。这是一个命令行交互式的程序,用户可以输入两个数字和操作符进行计算:
```c
#include <stdio.h>
// 函数声明用于执行加法、减法、乘法和除法
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
int main() {
double num1, num2;
char operation;
printf("请输入第一个数:");
scanf("%lf", &num1);
printf("请输入运算符 (+, -, *, /):");
scanf(" %c", &operation);
printf("请输入第二个数:");
scanf("%lf", &num2);
switch(operation) {
case '+':
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, add(num1, num2));
break;
case '-':
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, subtract(num1, num2));
break;
case '*':
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, multiply(num1, num2));
break;
case '/':
if (num2 != 0)
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, divide(num1, num2));
else
printf("错误:除数不能为零!\n");
break;
default:
printf("无效的运算符!\n");
}
return 0;
}
// 定义函数实现
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
if (b == 0)
return 0;
else
return a / b;
}
```
阅读全文