利用函数实现加减乘除计算器
方法一
#includeenum op{ EXIT, ADD, SUB, MUL, DIV};void menu(){ printf("1.add 2.sub.\n"); printf("3.mul 4.div.\n"); printf("0.exit\n");}int _add(int num1, int num2){ return num1 + num2;}int _sub(int num1, int num2){ return num1 - num2;}int _mul(int num1, int num2){ return num1 * num2;}int _div(int num1, int num2){ return num1 / num2;}int main(){ int input = 1; int num1 = 0; int num2 = 0; int ret = 0; while (input) { menu(); printf("请选择>"); scanf("%d", &input); switch (input) { case ADD: { printf("%请输入两个操作数"); scanf("%d%d", &num1, &num2); ret = _add(num1, num2); break; } case SUB: { printf("%请输入两个操作数"); scanf("%d%d", &num1, &num2); ret = _sub(num1, num2); break; } case MUL: { printf("%请输入两个操作数"); scanf("%d%d", &num1, &num2); ret = _mul(num1, num2); break; } case DIV: { printf("%请输入两个操作数"); scanf("%d%d", &num1, &num2); ret = _div(num1, num2); break; } case EXIT: { exit(0); break; } } printf("ret=%d\n", ret); }}
方法二
#includeenum op{ EXIT, ADD, SUB, MUL, DIV};void menu(){ printf("1.add 2.sub.\n"); printf("3.mul 4.div.\n"); printf("0.exit\n");}//参数和返回值类型均相同int _add(int num1, int num2){ return num1 + num2;}int _sub(int num1, int num2){ return num1 - num2;}int _mul(int num1, int num2){ return num1 * num2;}int _div(int num1, int num2){ return num1 / num2;}int main(){ int input = 1; int num1 = 0; int num2 = 0; int ret = 0; //转移表 int(*pfun[5])(int, int) = { 0, _add, _sub, _mul, _div }; //要求函数的参数和返回值类型均相同才能放到指针数组里 while (input) { menu(); printf("请选择>"); scanf("%d", &input); if (input != 0) { printf("请输入两个数:>"); scanf("%d%d", &num1, &num2); ret = pfun[input](num1, num2); printf("ret=%d\n", ret); } }}