使用回调函数实现一个简单的计算器;

时间:2023-01-09 21:56:23
一个小的计算程序,用了回调函数;查了很久才模模糊糊户的知道了回调函数的意思和用法!
#include<stdio.h>
//int add(int ,int )

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;
}

//下面这个函数我把他看作为中间函数(当然也许是错误的)也可以把他看成一个系统,当main中传来一个回调函数(像参数一样),他会先进入这个中间函数,然后这个中间函数这里通过函数指针去调用回调函数;
int func(int (*pfunc)(int , int),int a,int b)
{
int res = pfunc(a,b);
return res;
}

int main()
{
int a = 10;
int b = 20;
char ch;
int res;

scanf(
"%c",&ch);

switch(ch)
{
case'+':
res
= func(add,a,b); //把回调函数像参数一样传入中间函数func()。可以这么理解,在传入一个回调函数之前,中间函数是不完整的。换句话说,程序可以在运行时,通过登记不同的回调函数,来决定、改变中间函数的行为,也就是通过func()当中的函数指针pfunc()来指向不同的功能函数,从而调用;
break;

case'-':
res
= func(sub,a,b);
break;

case'*':
res
= func(mul,a,b);
break;

case'/':
res
= func(div,a,b);
break;

}
printf(
"%d\n",res);
putchar(
'\n');

return 0;
}