1、使用 if-else 结构实现的简单计算器
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("输入操作符 (+, -, *, /): ");
scanf("%c", &operator);
printf("输入两个数字: ");
scanf("%lf %lf", &num1, &num2);
if (operator == '+') {
result = num1 + num2;
} else if (operator == '-') {
result = num1 - num2;
} else if (operator == '*') {
result = num1 * num2;
} else if (operator == '/') {
if (num2 != 0)
result = num1 / num2;
else {
printf("Error! Division by zero.\n");
return 1;
}
} else {
printf("Error! 无效操作符.\n");
return 1;
}
printf("结果: %.2lf\n", result);
return 0;
}
参考文档:
2、使用 switch-case 结构实现的简单计算器
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("输出入操作符 (+, -, *, /): ");
scanf("%c", &operator);
printf("输入两个数: ");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0)
result = num1 / num2;
else {
printf("Error! Division by zero.\n");
return 1;
}
break;
default:
printf("Error! 无效操作符.\n");
return 1;
}
printf("结果: %.2lf\n", result);
return 0;
}
参考文档:C语言 switch case 语句
3、使用函数指针数组实现的简单计算器
#include <stdio.h>
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 a / b;
else {
printf("Error! Division by zero.\n");
return 0;
}
}
int main() {
char operator;
double num1, num2, result;
double (*operation[256])(double, double) = { NULL };
operation['+'] = add;
operation['-'] = subtract;
operation['*'] = multiply;
operation['/'] = divide;
printf("输入操作符 (+, -, *, /): ");
scanf("%c", &operator);
if (operation[(int)operator] == NULL) {
printf("Error! Invalid operator.\n");
return 1;
}
printf("输入两个数: ");
scanf("%lf %lf", &num1, &num2);
result = operation[(int)operator](num1, num2);
printf("结果: %.2lf\n", result);
return 0;
}
参考文档: