用转移表实现计算器的简单功能

因为用传统方法实现的时候,代码会显得过于繁琐。下面,是用转移表实现计算器功能的代码。(多文件形式)

头文件

#ifndef _CAL_H_
#define _CAL_H_

#pragma warning(disable:4996)
#include<stdio.h>
#include<Windows.h>

int my_add(int, int);
int my_sub(int, int);
int my_mul(int, int);
int my_div(int, int);

#endif

对应方法的实现

#include"cal.h"

int my_add(int x, int y)
{
	return x + y;

}
int my_sub(int x, int y)
{ 
	return x - y;
}
int my_mul(int x, int y)
{
	return x * y;
}
int my_div(int x, int y)
{
	return x / y;
}

主要的逻辑实现

#include"cal.h"

void menu()
{
	printf("###########################\n");
	printf("##  1.ADD        2.SLB   ##\n");
	printf("##  3.MUL        4.DIV   ##\n");
	printf("##               0.QUIT  ##\n");
	printf("###########################\n");
	printf("Plesae Enter:>");
}

int main()
{
	int(*p[4])(int,int) = { my_add, my_sub, my_mul, my_div };
	int quit = 0;
	while (!quit)
	{
		menu();
		int select = 0;
		scanf("%d", &select);

		if (select == 0)
		{
			quit = 1;
			continue;
		}
		if (select<1 && select>4)
		{
			quit = 1;
			continue;
		}
		int x = 0; int y = 0;
		printf("请输入两个数:");
		scanf("%d %d", &x, &y);
		int z=p[select - 1](x,y);
		printf("结果是:%d\n", z);

	}
	printf("byebye!\n");
	system("pause");
	return 0;
}

菜鸟一枚,水平有限,谢众位博友批评指正,不胜感激!

发布了14 篇原创文章 · 获赞 0 · 访问量 148

猜你喜欢

转载自blog.csdn.net/qq_41041036/article/details/103680882