帮我用C语言写一段计算器程序
时间: 2024-10-24 15:13:35 浏览: 22
当然可以,下面是一个简单的命令行计算器程序示例,它支持加减乘除四则运算:
```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 operator;
printf("请输入第一个数字: ");
scanf("%lf", &num1);
printf("请输入运算符 (+, -, *, /): ");
scanf(" %c", &operator);
printf("请输入第二个数字: ");
scanf("%lf", &num2);
switch(operator) {
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) { return a / b; }
```
运行这个程序,它会提示用户输入两个数字和运算符,然后计算并显示结果。
阅读全文