转移表——函数指针数组+枚举

所谓转移表就是由——函数指针数组、枚举 两部分一起完成的。

例如:简易计算器的实现,如下:

<span style="font-family:Courier New;">#include<stdio.h>

int add(int a,int b);
int sub(int a,int b);
int mul(int a,int b);
int div(int a,int b);
enum opera{ADD,SUB,MUL,DIV};  //定义枚举类型

int main(void)
{
printf("input the operation string:\n");//输入的字符串如13+24、33-256、27*2、12/3 的形式
char ch;
int flag_a = 0,flag_op =0,flag_b =0;
int a = 0,b = 0,result = 0;
char opera = 0;

enum opera op;//定义符号枚举变量
int (*fun[4])(int,int)= {add,sub,mul,div};//定义函数指针数组

while(ch = getchar(),ch !='\n')
{
	if(flag_op == 0 && ch >=48 && ch<=57)//操作数1
	{
		a = a*10 +(ch - '0');
		flag_a = 1;
	}
	else if(flag_a == 1&& flag_op == 0&& (ch == '+'||ch == '-' ||ch == '*' ||ch == '/'))//运算符
	{
		opera = ch;
		flag_op = 1;
	}
	else if(flag_op == 1 && ch >=48&&ch <=57)//操作数2
	{
		b = b*10+(ch -'0');
		flag_b = 1;
	}
	else   </span><span style="font-family: 'Courier New'; ">//意外之笔,输入格式不符合要求的字符 !</span><span style="font-family:Courier New;">
	{
		printf("the format you input is wrong !\n");
		return -1;
	}
}

if(flag_b == 0)//三部分没有输入完的 !
{
	printf("the format you input is wrong !\n");
	return -1;
}
	
switch(opera)  //确定操作符
{
	case '+': op = ADD; break;
	case '-':  op = SUB; break;
	case '*':  op = MUL; break;
	case '/':  op = DIV; break;
}

result = fun[op](a,b);  //计算
printf("the result = %d\n",result);

return 0;
}
int add(int a,int b)
{
	return a+b;
}

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

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

int div(int a,int b)
{
	return a/b;
}</span>
分好几次不同输入下的执行的结果如下:

12+36 
the result = 48

12-36
the result = -24

12*3
the result = 36

12/2
the result = 6

12
the format you input is wrong !

12-
the format you input is wrong !

12--3
the format you input is wrong !

-4
the format you input is wrong !

1a2-4
the format you input is wrong !




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值