#include <stdio.h> #include <stdlib.h> int _add(int a, int b) { return a + b; } int _sub(int a, int b) { return a - b; } int _mul(int a, int b) { return a*b; } int _div(int a, int b) { if (b == 0) { printf("除数位0\n"); } return a / b; } void menu() { printf("*************************\n"); printf("**** 1.add 2.sub ****\n"); printf("**** 3.mul 4.div ****\n"); printf("******** 0.exit *********\n"); printf("*************************\n"); } int main() { int input = 1; int num1 = 0; int num2 = 0; int ret = 0; while (input) { menu(); printf("请选择>:"); scanf("%d", &input); printf("请输入两个整数操作数>:"); scanf("%d%d", &num1, &num2); switch (input) { case 1: ret = _add(num1, num2); break; case 2: ret = _sub(num1, num2); break; case 3: ret = _mul(num1, num2); break; case 4: ret = _div(num1, num2); break; case 0: exit(EXIT_FAILURE); break; default: printf("选择错误,请重新选择.\n"); break; } printf("ret = %d\n", ret); } return 0; } 此外,也可以用枚举结构(enum)实现: #include <stdio.h> #include <stdlib.h> enum OP { EXIT, ADD, SUB, MUL, DIV }; int _add(int a, int b) { return a + b; } int _sub(int a, int b) { return a - b; } int _mul(int a, int b) { return a*b; } int _div(int a, int b) { if (b == 0) { printf("除数位0\n"); } return a / b; } void menu() { printf("*************************\n"); printf("**** 1.add 2.sub ****\n"); printf("**** 3.mul 4.div ****\n"); printf("******** 0.exit *********\n"); printf("*************************\n"); } int(*pfun[5])(int, int) = {0, _add, _sub, _mul, _div}; int main() { int input = 1; int num1 = 0; int num2 = 0; int ret = 0; while (input) { menu(); printf("请选择>:"); scanf("%d", &input); printf("请输入两个整数操作数>:"); scanf("%d%d", &num1, &num2); if (input >= 1 && input <= 4) { ret = pfun[input](num1, num2); } else if (input == 0) { exit(EXIT_FAILURE); } else { printf("选择错误\n"); } printf("ret = %d\n", ret); } return 0; }
时间: 2024-11-05 13:48:23