c++ - 计算结果出现奇怪的错误

标签 c++ math

我的计算结果似乎有这个奇怪的问题。当它应该是 1.375 时,我似乎总是得到 -0.125 的结果。这可能是我放置计算的方式吗?

下面是参与计算的.cpp文件:

位置数据.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;
}

任务计划.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;
}

关于如何解决这个奇怪的问题有什么想法吗?谢谢!

最佳答案

sunTypePercent 是小于 100 的 int 时,

(sunTypePercent/100) 始终为零,因为您正在进行整数除法。

您可能需要 sunTypePercentfloat(或 double)。

关于c++ - 计算结果出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19475112/

相关文章:

JavaScript:四舍五入 100

algorithm - 找到从一对数字中生成数字的最小步骤

将值映射到具有对数间距的单位刻度的算法

c++ - 具有所有组件可选的正则表达式,如何避免空匹配

c++ - 创建和释放 Qt 小部件对象

c++ - 如何从包含字符和整数的行中解析出整数

algorithm - 避免重复状态的搜索算法

c++ - 返回对前向声明类型的引用 (C++)

c++ - C++中 float 的限制

java - java如何进行负数的模计算?