参数错误将函数传递给另一个函数

时间:2013-09-13 16:53:15

标签: c++ fibonacci

#include <stdio.h>

double soma ( double a, double b){
    return a+b;
}

double mult ( double a, double b){
    return a*b;
}

double sub( double a, double b){
    return a-b;
}

double div ( double a, double b){
    return a/b;
}

double fib_ninja ( double (* fn)(double a, double b),int init ){
    int i=0;
    int tam=10;
    int acum = init;
    int ant=0;

    for (i=0 ; i<tam ; i++){
        acum = fn(acum,ant);
        ant = acum;
        printf ("%f",acum);
    }
    return acum;
}

int main(){
    int op;
    printf("escolha a operação desejada: 1(soma),2(multiplicação),3(subtraçaõ,4(divisão)) ");
    scanf("%d",&op);        
    if(op==1){ 
        fib_ninja((soma (6.0, 2.0)),0);
    }
    if(op==2){
        fib_ninja((mult ,6.0, 2.0),1);
    }
    if(op==3) {
        fib_ninja((sub ,6.0, 2.0),0);
    }
    if(op==4){
        fib_ninja((div ,6.0, 2.0),1);
    }

    return 0;
}

错误说

In function 'main':
Line 39: error: incompatible type for argument 1 of 'fib_ninja'
Line 42: error: incompatible type for argument 1 of 'fib_ninja'
Line 45: error: incompatible type for argument 1 of 'fib_ninja'
Line 48: error: incompatible type for argument 1 of 'fib_ninja'

来自此http://codepad.org/HTLeR6Jh

的链接

2 个答案:

答案 0 :(得分:3)

我试图推断你在这里要做什么,所以如果我曲解,请告诉我。

首先:acumant中的fib_ninja()需要double

第二:我不知道你要对价值6.02.0做些什么。它们未在签名中声明或在fib_ninja()中的任何位置使用,并且没有必要将它们传递给您的soma()等。函数,因为fib_ninja()显然是指一个函数指针,而不是从执行这些函数返回的double。从调用6.0中删除参数2.0fib_ninja(以及多余的括号),这样就可以消除错误。

例如为:
fib_ninja(soma, 0);
fib_ninja(mult, 1);

修好这些东西后,你的代码仍然不会做太多。如果您在处理更多问题后还有其他问题,请发布另一个问题。

答案 1 :(得分:0)

该程序有点困惑,如果没有一些更改,可能不会做任何有用的事情。我建议发布你想要回答的问题。

尽管如此,编译器的直接问题还是相当简单。

double Add(double x, double y);

int main()
{
    // The following will execute Add() and
    // pass the result to func1() as a double.
    func1(Add(1.0, 2.0));

    // The following will pass a function pointer
    // for Add() to func2()
    func2(Add);

    return 0;
}

我认为你想要上面的func2()之类的东西,但你写的更像是func1()

相关问题