简单计算器的实现与优化方法

题目:用程序实现一个简单计算器,能够进行加减乘除的基本运算

分析:利用分支语句进行选择不同的算法,对两个数进行不同的计算。输出对应函数返回的值,就是最终的计算结果。

代码如下

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

运行结果展示
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Thinker_serious/article/details/83620975