利用函数指针选择合适的被调用函数_契比雪夫多项式

来源:互联网 发布:网络客服工作指责 编辑:程序博客网 时间:2024/04/28 09:56
定义一个函数指针后,把一函数名(代表该函数入口地址)赋给函数指针,然后通过函数指针来间接调用该函数。由于一个函数指针可以先后指向不同的函数,因此可以利用这种方式来达到有条件地调用函数的目的。
例如:
已知契比雪夫多项式的定义如下所示:
x (n=1)
2*x*x-1 (n=2)
4*x*x*x-3*x (n=3)
8*x*x*x*x-8*x*x+1 (n=4)
要求:设计一个程序,从键盘输入整数n和浮点数x,并计算多项式的值。

# include <stdio.h>
int main(void)
{
float fn1(float x), fn2(float x), fn3(float x), fn4(float x);//函数声明
float (*fn)(float x);
float x;
int n;
printf("Input x:");
scanf("%f", &x);
printf("Input n:");
scanf("%d", &n);

switch(n)
{
case 1: fn = fn1; break;
case 2: fn = fn2; break;
case 3: fn = fn3; break;
case 4: fn = fn4; break;
default : printf("Date error!");
}
printf("Result = %f\n", fn(x)); //或写成(*fn)(x)
return 0;
}

float fn1(float x) { return x; }
float fn2(float x) { return 2*x*x-1; }
float fn3(float x) { return 4*x*x*x-3*x; }
float fn4(float x) { return 8*x*x*x*x-8*x*x+1; }


/*程序在VC++6.0中的执行结果:

--------------------------------------

Input x:3
Input n:4
Result = 577.000000

--------------------------------------

*/



0 0
原创粉丝点击