2013-10-20 132 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);