qq_30420749
许贤生
2020-02-06 14:56
采纳率: 100%
浏览 287

c语言中如何将拥有相同参数的不同函数函数指针作为另一个函数的参数?

c语言中如何将拥有相同参数的不同函数函数指针作为另一个函数的参数?

代码:

#include <stdio.h>
#include <time.h>
#include <math.h>

#define MAXN 10

clock_t start,stop;
double duration;

void myfunction(double(*func)(int,double,double),double a[]);
double f1(int n,double a[],double x);
double f2(int n,double a[],double x);

int main()
{
    int i=0;
    double a[MAXN];
    for(i=0;i<MAXN;i++)
        a[i] = (double)i;

    myfunction(f1,a);
    myfunction(f2,a);
    return 0;
}

void myfunction(double (*func)(int,double,double),double a[])
{
    start = clock();
    func(MAXN-1,a,1.1);
    stop = clock();
    duration = ((double)(stop - start))/CLK_TCK;
    printf("ticks1 = %f\n",(double)(stop - start));
    printf("duretion = %6.2e\n",duration);

}

double f1(int n,double a[],double x)
{
    int i;
    double p = a[0];
    for(i=0;i<=n;i++)
        p += (a[i] * pow(x,i));
    return p;
}

double f2(int n,double a[],double x)
{
    int i;
    double p = a[n];
    for(i=n;i>0;i--)
        p = a[i-1] + x * p;
    return p;
}

出错信息:
warning C4028: formal parameter 2 different from declaration
warning C4024: 'myfunction' : different types for formal and actual parameter 1
warning C4028: formal parameter 2 different from declaration
warning C4024: 'myfunction' : different types for formal and actual parameter 1
error C2115: 'function' : incompatible types
warning C4024: 'func' : different types for formal and actual parameter 2

请问错误原因是什么?怎么改才好?谢谢了!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • caozhy
    已采纳
    #include <stdio.h>
    #include <time.h>
    #include <math.h>
    
    #define MAXN 10
    
    clock_t start,stop;
    double duration;
    
    void myfunction(double(*func)(int,double*,double),double* a);
    double f1(int n,double *a,double x);
    double f2(int n,double *a,double x);
    
    int main()
    {
        int i=0;
        double a[MAXN];
        for(i=0;i<MAXN;i++)
            a[i] = (double)i;
    
        myfunction(f1,a);
        myfunction(f2,a);
        return 0;
    }
    
    void myfunction(double (*func)(int,double*,double),double*a)
    {
    double CLK_TCK = 1;
        start = clock();
        func(MAXN-1,a,1.1);
        stop = clock();
        duration = ((double)(stop - start))/CLK_TCK;
        printf("ticks1 = %f\n",(double)(stop - start));
        printf("duretion = %6.2e\n",duration);
    
    }
    
    double f1(int n,double a[],double x)
    {
        int i;
        double p = a[0];
        for(i=0;i<=n;i++)
            p += (a[i] * pow(x,i));
        return p;
    }
    
    double f2(int n,double a[],double x)
    {
        int i;
        double p = a[n];
        for(i=n;i>0;i--)
            p = a[i-1] + x * p;
        return p;
    }
    
    点赞 评论

相关推荐