我不明白为什么这个简单的程序输出乱码?

时间:2013-11-01 03:22:33

标签: c++ function parameters parameter-passing

#include <iostream>
#include <cmath>
using namespace std;
double T;
double V;
double WC(double T, double V);
void index(double WC(double T, double V));

    int main(void)
{
    cout<<"Please enter your T followed by your V"<<endl;
    cin>>T>>V;
    cout<<index;
}
double WC(double, double)
{
    if(V>4.8)
        return 13.12+0.6215*T-11.37*pow(V,0.16)+0.3965*T*pow(V,0.16);
    else
        return T;
}
void index(double WC(double,double))
{
    if (WC(T,V)<=0&&WC(T,V)>=-25)
    {
        cout<<"Discomfort";
    }
    if (WC(T,V)<-25&&WC(T,V)>=-45)
    {
        cout<<"Risk of skin freezing (frostbite)";
    }
    if (WC(T,V)<-45&&WC(T,V)>=-60)
    {
        cout<<"Exposed skin may freeze within minutes";
    }
    if (WC(T,V)<-60)
    {
        cout<<"Exposed skin may freeze in under 2 minutes";
    }
}

我不明白为什么这会输出像“010F11B8”这样的随机乱码,它只能根据温度和风速的输入打印出来。

2 个答案:

答案 0 :(得分:2)

你没有打电话给index,你正在打印它的地址。方法调用需要parens index()

答案 1 :(得分:1)

我认为您正在寻找的是:

working example

调用索引函数,你需要这样做:

#include <iostream>
#include <cmath>
using namespace std;
double T;
double V;
double WC(double T, double V);
void index(double WC(double T, double V));

int main(void)
{

    V = 5.0;
    T = -60.0;
    // declare a function pointer which accepts two doubles and returns a double
    double (*wcPtr)(double, double);

    // initialise function pointer
    wcPtr = &WC;

    cout << "Please enter your T followed by your V" << endl;

    // call function pointer
    index(wcPtr);
}
double WC(double T, double V)
{
    if(V>4.8)
        return 13.12+0.6215*T-11.37*pow(V,0.16)+0.3965*T*pow(V,0.16);
    else
        return T;
}
void index(double WC(double T,double V))
{
    if (WC(T,V)<=0&&WC(T,V)>=-25)
    {
        cout<<"Discomfort";
    }
    if (WC(T,V)<-25&&WC(T,V)>=-45)
    {
        cout<<"Risk of skin freezing (frostbite)";
    }
    if (WC(T,V)<-45&&WC(T,V)>=-60)
    {
        cout<<"Exposed skin may freeze within minutes";
    }
    if (WC(T,V)<-60)
    {
        cout<<"Exposed skin may freeze in under 2 minutes";
    }
}