先上代码
#include <stdio.h>
#include <string.h>
double add(double a, double b){
return a+b;
}
double sub(double a, double b){
return a-b;
}
double mul(double a, double b){
return a*b;
}
double div(double a, double b){
return a/b;
}
///
double (*oper_func[])(double, double) = {
add, sub, mul, div
};
int main()
{
int ifContinue=1;
int flag=1;
int oper;
double a,b;
double result;
while(flag){
printf("Operator:\n0:add 1:sub 2:mul 3:div\n");
scanf("%d",&oper);
if(oper>3||oper<0){
printf("input wrong!\n");
continue;
}
printf("a:");
scanf("%lf",&a);
printf("b:");
scanf("%lf",&b);
result = oper_func[oper](a, b);
printf("result is %lf\n", result);
printf("Continue or not:(y/n)\n");
getchar();//用于吃掉前面的‘回车’
scanf("%c",&ifContinue);
if(ifContinue=='n')
flag=0;
}
return 0;
}
《C和C指针》中说转换表就是一个函数指针数组。
double (*oper_func[])(double, double) = {
add, sub, mul, div
};
默认add是0,sub是1,mul是2,div是3。