2013-10-20 149 views
0

我的計算結果似乎有這個奇怪的問題。當它應該是1.375時,我似乎總是得到-0.125的結果。這可能是我放置計算的方式嗎?奇怪的錯誤與計算結果

下面是參與計算的.cpp文件:

LocationData.cpp
這是計算完成的部分。

float LocationData::computeCivIndex(string sunType,int planetNo,int moonNo,float particulatePercent,float plasmaPercent) { 
float civIndex; 
int sunTypePercent; 

if (sunType == "O") 
    sunTypePercent = 30; 
if (sunType == "B") 
    sunTypePercent = 45; 
if (sunType == "A") 
    sunTypePercent = 60; 
if (sunType == "F") 
    sunTypePercent = 75; 
if (sunType == "G") 
    sunTypePercent = 90; 
if (sunType == "K") 
    sunTypePercent = 80; 
if (sunType == "M") 
    sunTypePercent = 70; 

cout << sunTypePercent<< endl; 
//calculate the civIndex 
civIndex = ((sunTypePercent/100) - (particulatePercent+plasmaPercent)/200) * (planetNo+moonNo); 
return civIndex; 
} 

MissionPlan.cpp
這是計算方法被稱爲

void MissionPlan::computeCivIndex() { 
LocationData ld; 

string type; 
int planets,moons; 
float particulate,plasma; 

if (db.size() == 0) 
    cout << "No data! Please input statistical data before proceeding..." << endl; 
else { 
    for (vector<PointTwoD>::iterator itr = db.begin(); itr != db.end(); ++itr) { 
     ld = itr->getLocationData(); 
     type = ld.getSunType(); 
     planets = ld.getNoOfEarthLikePlanets(); 
     moons = ld.getNoOfEarthLikeMoons(); 
     particulate = ld.getAveParticulateDensity(); 
     plasma = ld.getAvePlasmaDensity(); 

     //i print out the values to check that it is the values i inputted beforehand(manually) 
     cout << type << endl; 
     cout << planets << endl; 
     cout << moons << endl; 
     cout << particulate << endl; 
     cout << plasma << endl; 

     itr->setCivIndex(ld.computeCivIndex(type,planets,moons,particulate,plasma)); 
    } 
} 
cout << "Computation complete! (" << db.size() << " records were updated)" << endl; 
} 

就如何解決這個奇怪的問題任何想法的一部分嗎?謝謝!

回答

4

(sunTypePercent/100)sunTypePercentint小於100時總是爲零,因爲您在進行整數除法。

您可能需要sunTypePercentfloat(或double)。

+0

感謝。這就是訣竅!現在我知道在處理數學時我必須小心整數! –

+0

@JoelSeah: - 您可以接受這個答案,以便顯示答案的一些屬性! :) –

2

變化

int sunTypePercent; 

float sunTypePercent; 

OR:

civIndex = ((sunTypePercent/100.0) - (particulatePercent+plasmaPercent)/200.0) * (planetNo+moonNo);