两个double类型的数相加时会出现小数点后有许多位数的情况,如2.2+4.4=6.60000005
我用NumberFormat限定了小数点的位数,发现并没有起作用
以下是我编写的复数相加
public class complex {
public static void main(String args[])
{
NumberFormat df=NumberFormat.getNumberInstance();
df.setMaximumFractionDigits(1);//设置小数点后面尾数为1
Scanner in = new Scanner(System.in);
double r11 = in.nextDouble();
double v11 = in.nextDouble();
double r22 = in.nextDouble();
double v22 = in.nextDouble();
complexnum a = new complexnum(r11,v11);
complexnum b = new complexnum(r22,v22);
if(a.getSubVertual(b)>=0)
{JOptionPane.showMessageDialog(null,"a="+a.getReal()+"+"+a.getVertual()+"*i\n"+
                           "b="+b.getReal()+"+"+b.getVertual()+"*i\n"+
                           "a+b="+df.format(a.getAddReal(b))+"+"+df.format(a.getAddVertual(b))+"*i\n"+
                           "a-b="+df.format(a.getSubReal(b))+"+"+df.format(a.getSubVertual(b))+"*i\n");}
if(a.getSubVertual(b)<0)
{JOptionPane.showMessageDialog(null,"a="+a.getReal()+"+"+a.getVertual()+"*i\n"+
                "b="+b.getReal()+"+"+b.getVertual()+"*i\n"+
                "a+b="+a.getAddReal(b)+"+"+a.getAddVertual(b)+"*i\n"+
                "a-b="+a.getSubReal(b)+"-"+Math.abs(a.getSubVertual(b))+"*i\n");}
}
}
class complexnum
{
private double real;
private double vertual;
public complexnum(double r,double v)
{
real = r;
vertual = v;
}
public double getReal()
{
return real;
}
public double getVertual()
{
return vertual;
}
public double getAddReal(complexnum m)
{
return real+m.real; 
}
public double getAddVertual(complexnum m)
{
return vertual+m.vertual;
}
public double getSubReal(complexnum m)
{
return real-m.real;
}
public double getSubVertual(complexnum m)
{
return vertual-m.vertual;
}
}

解决方案 »

  1.   

    不要指望 double 进行精确的计算,这是没有办法的,IEEE 754 就这样规定的。二进制数据没办法精确表示十进制小数。如果需要精确的计算,请使用 BigDecimal 类。
      

  2.   

    JOptionPane.showMessageDialog(null,"a="+a.getReal()+"+"+a.getVertual()+"*i\n"+
    "b="+b.getReal()+"+"+b.getVertual()+"*i\n"+
    "a+b="+df.format(a.getAddReal(b))+"+"+df.format(a.getAddVertual(b))+"*i\n"+
    "a-b="+df.format(a.getSubReal(b))+"+"+df.format(a.getSubVertual(b))+"*i\n");上面的代码红色标注有误
    当我输入1.1 2.2 3.3 4.4的时候,并没有我想要的结果
      

  3.   


    好吧,但是实验报告里给出的类成员的要求便是double型,NumberFormat确实有规范输出精度的作用,为什么在我的程序中不起作用来
      

  4.   

    你得到的结果是?还有这样df.format(a.getAddReal(b))得到的string类型的
      

  5.   

    http://happyran.zbpifa.com
    http://007ej.com/user.asp