首页 > 解决方案 > 当我只使用两个十进制数时,为什么在相加时会得到大的十进制数,如何在 Java 中修复它?

问题描述

我正在编写一个代码,它将使用数组中的数字并将它们相加。我只有两位小数的双打,但我仍然得到超过 6 个小数。我怎样才能解决这个问题?我的代码目前包括:

 //this is the array where I'll be getting the numbers from
public static double[] prijzen = new double[]{2.20,3.70,4.20,0.50,2.60,1.80}; 

//double where the numbers will be added and stored
public static double totaal = 0; 

 // a method that will calculate the total for me
 public static double TotaalPrijs(double x)
{
  totaal = totaal + x;  

  return totaal;
 }

该方法将在按下 JButton 时激活。其中一个按钮的代码如下所示

  private void BtnFrisdrankActionPerformed(java.awt.event.ActionEvent evt) 
  {                                             
    double prijs = prijzen[0]; 
    TotaalPrijs(prijs);
  }

标签: javaarraysdoublerounding

解决方案


推荐阅读