0

我正在尝试从函数返回一个值,但它返回的只是值 1。

假设在 5 中有 5 个参数computeCivIndex(),即使我对值进行硬编码,我收到的输出仍然是 1。

为什么会这样?

float LocationData::computeCivIndex()
{
     civNum1 = 45.0 / 100;
     civNum2 = 20 + 50;
     civNum3 = civNum2 / 200;
     civNum4 = civNum1 - civNum3;
     civNum5 = 5 + 10;


    return civNum;
}

//display data
void LocationData::displaydata()
{
cout << "CIV value: " << computeCivIndex << endl;
}
4

3 回答 3

5

你错过()cout << "CIV value: " << computeCivIndex() << endl;。有关大括号的重要性,您可以查看此链接

于 2013-10-20T17:30:53.690 回答
1

cout << "CIV 值:" << computeCivIndex << endl;

似乎正在打印函数的值(而不是返回值)。您需要将函数括号放入:

cout << "CIV 值:" << computeCivIndex() << endl;

于 2013-10-20T17:32:33.117 回答
0
//convert sunType to sunTypePercentage
float LocationData::computeCivIndex(string st, int earth, int moons, float particle, float plasma)
{

    float sunTypePercent;

    if(st == "Type 0")
    {
        sunTypePercent = 80.0;
    }
    else if(st == "Type B")
    {
        sunTypePercent = 45.0;
    }
    else if(st == "Type A")
    {
        sunTypePercent = 60.0;
    }
    else if(st == "Type F")
    {
        sunTypePercent = 75.0;
    }
    else if(st == "Type G")
    {
        sunTypePercent = 90.0;
    }
    else if(st == "Type K")
    {
        sunTypePercent = 80.0;
    }
    else if(st == "Type M")
    {
        sunTypePercent = 70.0;
    }

    // calculate CIV Value
    float civNum,civNum1,civNum2,civNum3,civNum4,civNum5;

    civNum1 = sunTypePercent / 100;
    civNum2 = plasma + particle;
    civNum3 = civNum2 / 200;
    civNum4 = civNum1 - civNum3;
    civNum5 = earth + moons;

    civNum = civNum4 * civNum5;


    return civNum;
}

//display data
void LocationData::displaydata()
{

    cout << "suntype: " << sunType << endl;
    cout << "earth: " << noOfEarthLikePlanets << endl;
    cout << "moons: " << noOfEarthLikeMoons << endl;
    cout << "particle: " << aveParticulateDensity << endl;
    cout <<"density: " << avePlasmaDensity << endl;
    cout << "CIV value: " << computeCivIndex()<< endl;
}

这是我遇到问题的实际代码。对于 computeCivIndex() 函数,它实际上是我的 LocationData.h 文件中公共 LocationData 类下的静态变量,看起来像这样。

静态浮点计算 CivIndex(字符串 st,int earth,int moons,floatparticle,float plasma);

所以为了从函数中检索值我应该这样做吗?

cout << "CIV 值:" << LocationData.computeCivIndex() << endl;

于 2013-10-21T04:47:03.877 回答