【问题标题】:Java float array gives me multiple copies of same resultJava浮点数组给了我相同结果的多个副本
【发布时间】:2017-10-06 14:56:30
【问题描述】:
public class SelectionEngine {
    int[] fitness;
    int percentage;
    float[] fortunePercentage;

    SelectionEngine(int[] fitnessArray){
        this.fitness=fitnessArray;

    }

   float[] createFortuneWheel(){

 [...]
        fortunePercentage = new float[this.fitness.length];
        for(int i=0;i<fitness.length;i++){
            perc= (float) this.fitness[i]/maxVal;
           sigma += 1-(perc);
        }

//now we load fortunePercentage table with percentages
       for(int i=0;i<this.fitness.length;i++) {
           perc= (float) (this.fitness[i]/maxVal);
           fortunePercentage[i]=((1-perc)/sigma);
       }

       return fortunePercentage;

    }
}

在我的主类中调用此代码后,我想将 fortunePercentage 分配给一个数组,如下所示:

float[] fortuneTest =new float[fitnessTable.length];
    SelectionEngine selector = new SelectionEngine(fitnessTable);
    fortuneTest=selector.createFortuneWheel();

我得到一个充满相同结果的数组,除了一个零,这是由于数学而必须发生的。我的fitness[] 表充满了不同的结果,它们是整数,fortunePercentage 应该包含一个表,其中包含每个相应适应度值的百分比,对于最差的(最长的)它应该自动评估为零。

相反,我得到了我的 fortuneTest 数组,其中包含相同的结果和一个零(或者两个或三个,如果我在我的健身表中得到三个相等的最差值)。为什么? 数组在 java 中的工作方式与在 c++ 中的工作方式不同吗?

【问题讨论】:

  • this.fitness[i]/maxVal; 如果maxValint,你会在这里得到整数除法。投一到float
  • perc= (float) (this.fitness[i]/maxVal); 所以,我没有正确转换类型?
  • 可以发一下内容吗?
  • 第一次做对了:perc= (float) this.fitness[i]/maxVal;,第二次做错了:perc= (float) (this.fitness[i]/maxVal);
  • float(5/5) = 1.0 所以约翰尼的观点是正确的。您在除法后铸造浮动。除法的结果已经是整数,并且您的转换将点零 (.0) 添加到结果

标签: java arrays object floating-point


【解决方案1】:

而不是这个:

perc= (float) this.fitness[i]/maxVal;

试试这个:

perc= (float) (this.fitness[i]/maxVal);

【讨论】:

  • 实际上,它看起来正好相反。在您的第二行中,您将整数除法(其结果无效)转换为浮点数。在第一个中,您调用浮点除法。我想。
猜你喜欢
  • 2013-01-31
  • 2013-03-24
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
相关资源
最近更新 更多