【问题标题】:Argument errors passing function to another function [closed]将函数传递给另一个函数的参数错误[关闭]
【发布时间】:2013-09-13 16:53:15
【问题描述】:
#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的链接

【问题讨论】:

  • 当我读到一个拼写错误的标题时,我总觉得自己被骗了。
  • 始终使用您使用的语言进行标记,并且请使用更具描述性的标题。
  • 对不起,我的英语不好,我来自巴西。 ;/这里的教育很糟糕。
  • double fib_ninja ( double (* fn)(double a, double b),int init ){ 你真的可以声明这样的方法吗......?
  • @progenhard:当然可以……

标签: c++ fibonacci


【解决方案1】:

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

首先:acumant 中的 fib_ninja() 必须是 double

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

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

修复这些问题后,您的代码仍然不会做太多事情。如果您在进行更多工作后还有其他问题,请发布另一个问题。

【讨论】:

    【解决方案2】:

    该程序有点混乱,如果不进行一些更改,可能不会做任何有用的事情。我建议发布您要回答的问题。

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

    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()

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2020-10-03
      • 2014-01-06
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多