| #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}, |
| {"-", fun_sub}, |
| {"*", fun_mul}, |
| {"/", fun_div} |
| }; |
| |
| int fun_table_len = sizeof(fun_table) / sizeof(fun_table[0]); |
| |
| |
| 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; |
| } |
| |
| |
| 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[]) |
| { |
| |
| 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)); |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下