#include <stdio.h>
float add (float a,float b)
{
return a + b;
}
float sub (float a,float b)
{
return a - b;
}
float mul (float a,float b)
{
return a * b;
}
float div (float a,float b)
{
return a / b;
}
//回调函数
float func (float (*p)(float a,float b),float a,float b)//函数指针作为函数参数
{
return p(a,b);
}
float main()
{
float a;
float b;
float res;
char ch;
printf ("input num1:");
scanf ("%f",&a);
printf ("input num2:");
scanf ("%f",&b);
printf ("input op:");
scanf ("%c",&ch);
switch (ch)
{
case '+':
res = func (add,a,b);//函数名是地址,代表函数空间的入口地址,可以用指针接收
break;
case '-':
res = func (sub,a,b);
break;
case '*':
res = func (mul,a,b);
break;
case '/':
res = func (div,a,b);
break;
}
printf ("res = %g\n",res);
return 0;
}
linux C 使用函数指针和回调函数实现简易计算器
猜你喜欢
转载自blog.csdn.net/qq_19004627/article/details/82911109
今日推荐
周排行