#include <stdio.h>
typedef int (*CalculationFunc)(int, int);
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
void calculator(int a, int b, char operator, CalculationFunc callback) {
int result = 0;
switch(operator) {
case '+':
result = callback(a, b);
break;
case '-':
result = callback(a, b);
break;
default:
printf("Invalid operator\n");
return;
}
printf("%d %c %d = %d\n", a, operator, b, result);
}
int main() {
int a, b;
char operator;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Enter an operator (+ or -): ");
scanf(" %c", &operator);
if(operator == '+' || operator == '-') {
CalculationFunc func = (operator == '+') ? add : subtract;
calculator(a, b, operator, func);
} else {
printf("Invalid operator\n");
}
return 0;
}
笔记-回调方法在C语言中的应用
最新推荐文章于 2024-08-29 16:39:06 发布