在if语句中进行比较时,双倍超出范围

时间:2013-05-28 11:51:58

标签: java

以下代码在尝试保存分数时给出了奇怪的结果(它正在添加大量值,就像if语句失败一样)。

double EndScore = (double)(mScoreManager.getScore());

    if(mWorldCounterBox.getCurrentAlivePopulationPercent() < 97.0)
    {
        EndScore += (mWorldCounterBox.getCurrentAlivePopulationPercent()) * 100.00;
    }

    System.out.println(mWorldCounterBox.getCurrentAlivePopulationPercent()); //Output: 1.0544652507298142E-7
    System.out.println(EndScore); //Output: 1.0000105446525074

    //Increase score per dead %.
    if(mWorldCounterBox.getCurrentAlivePopulationPercent() < 0.1)
    {
        EndScore += 20000.0;
    }
    System.out.println(EndScore); //Outout 20001.000010544652 -- WRONG HERE
    SettingsSaveLoad.setCountryScore(mCurrentWorld, (float)(EndScore));

2 个答案:

答案 0 :(得分:1)

满足两个时间的条件。

如果值小于0.1,则还小于97.0

你猜错了我的条件

mWorldCounterBox.getCurrentAlivePopulationPercent()小于0.1。

如果第一个条件满足

if(mWorldCounterBox.getCurrentAlivePopulationPercent() < 97.0)  //mWorldCounterBox.getCurrentAlivePopulationPercent()  <97.0  true

它总是进入第二个条件

  if(mWorldCounterBox.getCurrentAlivePopulationPercent() < 0.1)    //mWorldCounterBox.getCurrentAlivePopulationPercent()  <0.1  true

方注:

请遵循java命名约定.Ex: EndScore endScore

答案 1 :(得分:1)

  
    

的System.out.println(mWorldCounterBox.getCurrentAlivePopulationPercent()); //输出:1.0544652507298142E-7

  

表示mWorldCounterBox.getCurrentAlivePopulationPercent()1.0544652507298142 * ((10)^-7) 小于0.1

SO之后

EndScore += 20000.0; //1.0000105446525074+ 20000.0

EndScore变为20001.000010544652