我正在尝试从函数返回一个值,但它返回的值是值1.
假设在computeCivIndex()
中有5个参数,即使我对值进行了硬编码,我收到的输出仍然是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;
}
答案 0 :(得分:5)
您遗漏()
中的cout << "CIV value: " << computeCivIndex() << endl;
。
对于大括号的重要性,您可以查看this link。
答案 1 :(得分:1)
cout&lt;&lt; “CIV值:”&lt;&lt; computeCivIndex &lt;&lt; ENDL;
似乎是打印函数的值(不是返回值)。您需要将函数括号放在:
中cout&lt;&lt; “CIV值:”&lt;&lt; computeCivIndex()&lt;&lt; ENDL;
答案 2 :(得分: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类下的静态,看起来像这样。
static float compute CivIndex(string st,int earth,int moons,float particle,float plasma);
所以为了从函数中检索值,我应该这样做吗?
cout&lt;&lt; “CIV值:”&lt;&lt; LocationData.computeCivIndex()&lt;&lt; ENDL;