【C語言】實現一個計算器(兩種方式)
阿新 • • 發佈:2018-11-16
-
1.使用switch…case…語句實現
#define _CRT_SECURE_NO_DEPRECATE 1 #include <stdio.h> #include <stdlib.h> int add(int x, int y) { return x + y; } int sub(int x, int y) { return x - y; } int mul(int x, int y) { return x * y; } int div(int x, int y) { return x / y; } int main() { int x, y; int input = 1; int ret = 0; while (input) { printf("*************************\n"); printf("**** 1.add 2.sub ****\n"); printf("**** 3.mul 4.div ****\n"); printf("*************************\n"); printf("請選擇:"); scanf("%d", &input); switch (input) { case 1: printf("請輸入運算元:"); scanf("%d %d", &x, &y); ret = add(x, y); break; case 2: printf("請輸入運算元:"); scanf("%d %d", &x, &y); ret = sub(x, y); break; case 3: printf("請輸入運算元:"); scanf("%d %d", &x, &y); ret = mul(x, y); break; case 4: printf("請輸入運算元:"); scanf("%d %d", &x, &y); ret = div(x, y); break; default: printf("選擇錯誤\n"); break; } printf("%d\n", ret); } system("pause"); return 0; }
-
2.使用函式指標陣列實現
因為加減乘除四個函式的函式型別都一樣,可以把它們的地址放在一個函式指標數組裡面,通過陣列的下標來訪問每個函式。
具體程式碼如下:
#define _CRT_SECURE_NO_DEPRECATE 1 #include <stdio.h> #include <stdlib.h> int add(int x, int y) { return x + y; } int sub(int x, int y) { return x - y; } int mul(int x, int y) { return x * y; } int div(int x, int y) { return x / y; } int main() { int x, y; int input = 1; int ret = 0; int(*p[5])(int x, int y) = { 0, add, sub, mul, div };//轉移表 while (input) { printf("*************************\n"); printf("**** 1.add 2.sub ****\n"); printf("**** 3.mul 4.div ****\n"); printf("*************************\n"); printf("請選擇:"); scanf("%d", &input); if (input<4 && input>1) { printf("請輸入運算元:"); scanf("%d %d", &x, &y); ret = (*p[input])(x, y); } else printf("輸入有誤\n"); printf("ret = %d", ret); } system("pause"); return 0; }