模拟实现计算器(switch函数实现与转移表实现)
switch函数实现:
#include <stdio.h>
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;
}
int main()
{
int x, y;
int input = 1;
int ret = 0;
do
{
printf("*************************\n");
printf(" 1:add 2:sub \n");
printf(" 3:mul 4:div \n");
printf(" 0:exit \n");
printf("*************************\n");
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
printf("输⼊操作数:");
scanf("%d %d", &x, &y);
ret = add(x, y);
printf("ret = %d\n", ret);
break;
case 2:
printf("输⼊操作数:");
scanf("%d %d", &x, &y);
ret = sub(x, y);
printf("ret = %d\n", ret);
break;
case 3:
printf("输⼊操作数:");
scanf("%d %d", &x, &y);
ret = mul(x, y);
printf("ret = %d\n", ret);
break;
case 4:
printf("输⼊操作数:");
scanf("%d %d", &x, &y);
ret = div(x, y);
printf("ret = %d\n", ret);
break;
case 0:
printf("退出程序\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
return 0;
}
我们能明显感觉到代码不够高效,代码太冗长了。
那有没有一个写一段就能够让四个运算避免这些重复的东西呢?
好!这个时候就要祭出转移表了!
转移表实现:
什么是转移表?
其实很简单,它所指的就是运用函数指针数组以数组方式去调用里面的函数,从而在某些情况下替代冗长的switch函数,就叫转移表
代码实现:
#include<stdio.h>
int add(int x, int y)
{
return x + y;
}
int sub(int x, int y)
{
return x - y;
}
int mul(int x, int y)
{
return x * y;
}
int div(int x, int y)
{
return x / y;
}
int main()
{
int (*arr[5])(int x, int y) = { 0,add,sub,mul,div };
do
{
printf("*****************************\n");
printf("******1. add 2. sub**********\n");
printf("******3. mul 4. div**********\n");
printf("****** 0. exit **********\n");
printf("*****************************\n");
printf("请选择\n");
int input = 0;
scanf("%d", &input);
if (input >= 1 && input <= 4)
{
int x = 0, y = 0;
printf("请输入操作数\n");
scanf("%d%d", &x, &y);
int ret = (*arr[input])(x, y);
printf("%d\n", ret);
break;
}
else if (input == 0)
{
printf("退出计算器\n");
break;
}
else
{
printf("输入错误,请重新输入\n");
}
} while (1);
return 0;
}