- 静态结构体数组式构建
- 链表式构建
- 链接式构建
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 加
double fun_add(double data_front, double data_back)
{
return data_front + data_back;
}
// 减
double fun_sub(double data_front, double data_back)
{
return data_front - data_back;
}
// 乘
double fun_mul(double data_front, double data_back)
{
return data_front * data_back;
}
// 除
double fun_div(double data_front, double data_back)
{
if(0 == data_back) return 0;
return data_front / data_back;
}
// 定义表驱动数据结构
typedef struct {
char *id;
double (*callback)(double, double);
}test_fun;
// 初始化表
const test_fun fun_table[] = {
{"+", fun_add}, // id, callback function
{"-", fun_sub},
{"*", fun_mul},
{"/", fun_div}
};
// 计算表长度
int fun_table_len = sizeof(fun_table) / sizeof(fun_table[0]); // 计算表长度
// 遍历表id, 执行对应function
double cal_fun(const char *id, double data_front, double data_back) {
for (int i= 0; i < fun_table_len; i++) {
if (strcmp(fun_table[i].id, id) == 0) {
return fun_table[i].callback(data_front, data_back);
}
}
return 0;
}
// if else方法,判断运算符,执行对应函数
double cal_fun_if(const char *id, double data_front, double data_back)
{
if (strcmp("+", id) == 0) { // +
return fun_add(data_front, data_back);
} else if (strcmp("-", id) == 0) { // -
return fun_sub(data_front, data_back);
} else if (strcmp("*", id) == 0) { // *
return fun_mul(data_front, data_back);
} else if (strcmp("/", id) == 0){ // /
return fun_div(data_front, data_back);
}
return 0;
}
int main(int argc, char *argv[])
{
// test this
double front = 20, back = 5;
printf("if-else Methods test as follow: \n");
printf("%.2f + %.2f = %.2f\n", front, back, cal_fun_if("+", front, back));
printf("%.2f - %.2f = %.2f\n", front, back, cal_fun_if("-", front, back));
printf("%.2f * %.2f = %.2f\n", front, back, cal_fun_if("*", front, back));
printf("%.2f / %.2f = %.2f\n", front, back, cal_fun_if("/", front, back));
printf("\n");
printf("Table-Driven Methods test as follow: \n");
printf("%.2f + %.2f = %.2f\n", front, back, cal_fun("+", front, back));
printf("%.2f - %.2f = %.2f\n", front, back, cal_fun("-", front, back));
printf("%.2f * %.2f = %.2f\n", front, back, cal_fun("*", front, back));
printf("%.2f / %.2f = %.2f\n", front, back, cal_fun("/", front, back));
}
- ()[https://zhuanlan.zhihu.com/p/615915687]
- ()[https://blog.csdn.net/qq_33471732/article/details/113787734]