函数指针

来源:互联网 发布:淘宝衣服褪色解释 编辑:程序博客网 时间:2024/06/06 16:42
#include <stdio.h>
#include <stdlib.h>
float Integral(float(*f)(float),float a,float b);
float Function1(float x);
float Function2(float x);
int main()
{
    int n,c;/*定义变量*/
    float a,b,result,x1=0.0,x2=1.0;/*定义变量*/
    float x3=0.0,x4=3.0;
    loop:/*设置goto标记*/
    printf("please choose the function you want calculate number:n (1 or 2) \n");/*输出提示*/
    int ret=scanf("%d",&n);
    if(ret!=1)
    {
        printf("Input Data Type Error!\n");
        fflush(stdin);
        return 0;
    }
    getchar();/*读取空格*/
    if(n<=0||n>2)/*条件判断*/
    {
    printf("the input is wrong please input the number of n again (1 or 2)  \n:");/*输出提示*/
    scanf("%d",&n);
    getchar();
    }
    if(n==1)
    {
    result=Integral(Function1,x1,x2);/*计算结果*/
    printf("the result is %f",result);
    }
    if(n==2)
    {
    result=Integral(Function2,x3,x4);
    printf("the result is %f\n",result);
    }
    printf("do you want again or exit:1 represent again");/*判断是否再次输入*/
    scanf("%d",&c);
    getchar();
    if(c==1)
    goto loop;/*重新执行一遍*/
    else
    return 0;
}
float Integral(float(*f)(float),float a,float b)/*定义函数指针*/
{
  float s,h;
  int n=100,i;
  s=((*f)(a)+(*f)(b))/2;/*计算梯形面积之一*/
  h=(b-a)/n;
  for(i=1;i<n+1;i++)
  {
  s+=(*f)(a+i*h);/*计算梯形面积*/
  }
  return s*h;
}
float Function1(float x)
{
    return 1+x*x;/*构造函数*/
}
float Function2(float x)
{
    return x/(1+x*x);/*构造函数*/
}
1 0
原创粉丝点击