#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; }