计算结果出现奇怪的错误

时间:2013-10-20 07:54:32

标签: c++ math

我的计算结果似乎有这个奇怪的问题。当它应该是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;
}

关于如何解决这个奇怪问题的任何想法?谢谢!

2 个答案:

答案 0 :(得分:4)

(sunTypePercent/100)sunTypePercent小于100时,

int始终为零,因为您正在进行整数除法。

您可能需要sunTypePercent成为float(或double)。

答案 1 :(得分:2)

更改

int sunTypePercent;

float sunTypePercent;

OR:

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