初学者,在此记录
如下代码
double a=4.8;
double b=3;
double c=1.6;
System.out.println(a);
System.out.println(b);
System.out.println(a/b);
System.out.println(a / b == c);
运行结果本应该是1.6,但实际输出为
由于java虚拟机导致的误差出现了
解决方法
如果是要判断相等的话用相减绝对值小于一定精度来判断
double a=4.8;
double b=3;
double c=1.6;
System.out.println(a);
System.out.println(b);
System.out.println(a/b);
System.out.println(Math.abs(a - c) < 0.00001);
如果是要得出一个正确的值,大概是用BigDecimal类型?
double a = 4.8;
double b = 3;
double c = 1.6;
BigDecimal aa = BigDecimal.valueOf(a);
BigDecimal bb = BigDecimal.valueOf(b);
BigDecimal cc = BigDecimal.valueOf(c);
System.out.println(aa);
System.out.println(bb);
System.out.println(cc);
System.out.println(aa.divide(bb));
System.out.println(aa.divide(bb).equals(cc));
Comments NOTHING