1. 程式人生 > >簡單計算器的實現與優化方法

簡單計算器的實現與優化方法

題目:用程式實現一個簡單計算器,能夠進行加減乘除的基本運算

分析:利用分支語句進行選擇不同的演算法,對兩個數進行不同的計算。輸出對應函式返回的值,就是最終的計算結果。

程式碼如下

#include <stdio.h>

int DIV(int a,int b)
{
	return a / b;
}

int MUL(int a, int b)
{
	return a * b;
}

int SUB(int a, int b)
{
	return a - b;
}

int ADD(int a,int b)
{
	return a + b;
}

void menu
() { printf("****************************\n"); printf("***1.ADD 2.SUB*****\n"); printf("***3.MUL 4.DIV*****\n"); printf("******** 0.EXIT **********\n"); } int main() { int input = 0; int x, y; printf("input two number-> \n"); scanf("%d%d",&x,&y); do { menu()
; printf("enter your chioce-> \n"); scanf("%d",&input); switch (input) { case 1: printf("%d + %d = %d", x, y, ADD(x, y)); break; case 2: printf("%d - %d = %d", x, y, SUB(x, y)); break; case 3: printf("%d * %d = %d", x, y, MUL(x, y)); break; case 4: printf(
"%d / %d = %d", x, y, DIV(x, y)); break; case 0: printf("EXIT"); break; default: printf("enter erorr,please enter a newnumber ->\n"); break; } printf("\n"); } while (input); return 0; }

用函式指標陣列實現:(轉移表)

分析:定義一個函式指標陣列,存放加減乘除四個函式的地址,選擇對應的函式地址,通過指標進行解引用就可以得到函式的值,即為需要求解的值。

函式指標陣列的定義方法:int (*p[5])(int x, int y) = {0, ADD, SUB, MUL, DIV}

程式碼如下

#include <stdio.h>

int DIV(int a, int b)
{
	return a / b;
}

int MUL(int a, int b)
{
	return a * b;
}

int SUB(int a, int b)
{
	return a - b;
}

int ADD(int a, int b)
{
	return a + b;
}

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("********  0.EXIT  **********\n");
		printf("請選擇-> ");
		scanf("%d",&input);
		if ((input <= 4 && input >= 1))
		{
			printf("請輸入運算元 ");
			scanf("%d %d", &x, &y);
			ret = (*p[input])(x, y);
		}
		else
			printf("輸入錯誤,請重新輸入 ");
		printf("ret = %d\n",ret);
	}
	return 0;
}

執行結果展示
在這裡插入圖片描述