1. 定义typedef int (*fp) (type para1...)
2. 使用fp myfp = 0;
3. 调用if(myfp){ myfp(...); }
问题:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数 求1/1+1/3+...+1/n(利用指针函数)
#include <stdio.h>
typedef float (*function_pointer_t) ( int arg1 );
float peven(int n)
{
float s = 1;
int i;
for(i=2;i<=n;i+=2)
s+=1/(float)i;
return(s);
}
float podd(int n)
{
float s = 0;
int i;
for(i=1;i<=n;i+=2)
s+=1/(float)i;
return(s);
}
float dcall(function_pointer_t fp,int n)
{
float s;
s = fp(n);
return(s);
}
int main()
{
function_pointer_t fp;
float sum;
int n;
scanf("%d",&n);
if(n%2==0)
fp = peven;
else
fp = podd;
sum = dcall(fp,n);
printf("%f\n",sum);
return 0;
}
运行结果: