class test {
public static void main(String args[]) {
double bottomStart = 2;
double bottomEnd = 3;
for (; bottomStart < bottomEnd; bottomStart += 0.1) {
System.out.println(bottomStart);
}
}
输出结果为:
2.0
2.1
2.2
2.3000000000000003
2.4000000000000004
2.5000000000000004
2.6000000000000005
2.7000000000000006
2.8000000000000007
2.900000000000001
想问问为什么会出现这种误差,怎么样才能输出正常的从2.0~3.0?谢谢各位高手了 :)
public static void main(String args[]) {
double bottomStart = 2;
double bottomEnd = 3;
for (; bottomStart < bottomEnd; bottomStart += 0.1) {
System.out.println(bottomStart);
}
}
输出结果为:
2.0
2.1
2.2
2.3000000000000003
2.4000000000000004
2.5000000000000004
2.6000000000000005
2.7000000000000006
2.8000000000000007
2.900000000000001
想问问为什么会出现这种误差,怎么样才能输出正常的从2.0~3.0?谢谢各位高手了 :)
class temp {
public static void main(String args[]) {
double bottomStart = 2;
double bottomEnd = 3;
for (int i=1;i<11;i++) {
System.out.println(bottomStart+0.1*i);
}
}
}
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
在网上查的,这样就可以精确计算了
import java.math.*;
double bottomStart = 2;
double bottomEnd = 3;
BigDecimal start = new BigDecimal(bottomStart);
BigDecimal end = new BigDecimal(bottomEnd);
for (; start.compareTo(end) ==-1; start=start.add(new BigDecimal("0.1"))) {
System.out.println(start);
}