【问题标题】:I don't understand why this simple program is outputting gibberish? [closed]我不明白为什么这个简单的程序会输出乱码? [关闭]
【发布时间】:2013-11-12 06:29:45
【问题描述】:
#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”这样的随机乱码,它只是应该根据输入的温度和风速打印一些东西。

【问题讨论】:

  • 你没有调用你的index函数并打印出index函数的地址
  • 假设您使用的是 UNIX/Linux,这可能会有所帮助:sourceware.org/gdb/current/onlinedocs/gdb
  • 详细说明Ed S的观点:T是什么? V 是什么? WC 是什么?您只使用一个提示并同时输入而不是提示输入提示输入?等等……

标签: c++ function parameters parameter-passing


【解决方案1】:

您不是在呼叫index,而是在打印它的地址。方法调用需要括号index()

【讨论】:

  • 几乎和我的措辞一样...顺便说一句,index 接受论点
  • @BryanChen:我知道确实如此。您应该发布答案而不是评论。
  • 我试过 cout
  • @user2923961:你的函数签名应该是index(double (*f)(double, double));,也就是说,它需要一个指向函数的指针,该函数需要两个双精度并返回一个双精度
【解决方案2】:

我认为您正在寻找的是:

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";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2022-07-15
    • 1970-01-01
    相关资源
    最近更新 更多