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

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

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

代码如下

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值