2015-07-06 108 views
-4

我的程序将温度从华氏温标转换为Celcius标度,最后转换为绝对值标尺。错误:无法将'float(*)(int)'转换为'float'

#include <iostream> 
#include <cmath> 
#include <iomanip> 
using namespace std; 

int farh; 

float cels(int a) 
{ 
    float c; 
    const int m0 = 32; 
    const float m1 = 0.5555; 

    c=(a-m0)/m1; 
    return c; 
} 

float ab(float a) 
{ 
    const float m2 = 273.15; 
    float d; 

    d=a-m2; 
    return d; 
} 

int main() { 
    const int WIDTH = 16; 

    cout << setiosflags (ios :: left); 
    cout << setw(WIDTH) << "Fahrenheit" << setw(WIDTH) << "Celcius" << setw(WIDTH) << "Absolute Value" << '\n'; 

    cout.setf(ios::fixed); 
    cout.precision(2); 

    for (farh = 0 ; farh <= 300 ; farh = farh + 20) { 
     cout.width(16); 
     cout << farh << cels(farh) << ab(cels) << "\n"; 
    } 

    return 0; 
} 

我收到编译时错误信息是:

d26.cc: In function ‘int main()’: 
d26.cc:38:40: error: cannot convert ‘float (*)(int)’ to ‘float’ for argument ‘1’ to ‘float ab(float)’ 
    cout << farh << cels(farh) << ab(cels) << "\n"; 

我为什么会收到这个错误?

回答

10

ab需要float并返回一个float

float ab(float a) 

cels不是float,它是一个函数:

float cels(int a) 

你可能是指

ab(cels(farh)) 

或者采取EMPORARY:

float cur_cels = cels(farh); 
cout << farh << cur_cels << ab(cur_cels) << "\n"; 

侧面说明,ab或许应该被命名为kelvin

+0

@BAarry 与ab(cels(farh))完美搭配。 –

1

其实你已经传递了一个funtion指针给ab。如果你的目的是传递给函数(!显然不是),你可以使用下面的语法:

float ab(float(*callback)(int),int pass) { 
    callback(pass); /* It calls the function indirectly with <pass> */ 
} 

其伟大的菜单制作,例如,如果你有两个选择:1。 华氏到细胞 2.华氏到开尔文这将是有用的

您可以搜索回调函数在谷歌C