2013-10-20 33 views
0

我試圖從一個函數返回一個值,返回值,但所有這回是值1C++的功能

它假設有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; 
} 
+0

'civNum'未初始化。 –

+0

但你正在返回'civNum',而不是函數中的任何值... – 0x499602D2

+0

什麼是'civNum',它是如何在'computeCivIndex()'中修改的?添加相關代碼。 – Kunal

回答

5

你錯過了()cout << "CIV value: " << computeCivIndex() << endl;。 對於大括號的重要性,你可以檢查this link

+2

對沒有'()'的情況進行一些解釋會很好。 – jrok

+0

'civNum'沒有在函數中使用 – P0W

+0

沒有'()',一個指向該方法的指針被傳遞給cout(作爲void *)。 – xorguy

1

COUT < < 「CIV值:」 < < computeCivIndex < < ENDL;

似乎正在打印函數的值(而不是返回值)。你需要把功能括號:

COUT < < 「CIV值:」 < < computeCivIndex() < < ENDL;

+0

,因爲我在computeCivIndex中有5個參數,所以我需要放入cout的5個參數? – user2900611

+0

err ... no :)我的(也是Igor Popov)意思是寫入沒有括號的函數名稱不會「調用」函數,它只是返回函數地址(即,您正在打印函數的值)。如果在函數的末尾加上括號,則這是調用函數並將函數計算的值返回給cout的正確語法。 –

+0

也像其他人所提到的那樣,您的civNum本身是由函數返回的,但其值從未改變。在返回之前,您需要爲此變量分配一個新值。例如:'civNum = civNum1 + civNum5;' –

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 < < 「CIV值:」 < < LocationData.computeCivIndex()< < ENDL;