本问题用到代码如下:
public class Count {
public static void main(String[] args) {
final int START = 2000000000;
int count = 0;
for (float f = START; f < START + 50; f++) {
count++;
}
System.out.println(count);
}
}
它的输出,应该是50吧。错,居然输出的是0,真是不可思议。(TODO)以下就分析原因!
int 向 float 强制转化,或 long 向 double 强制转化,都会丢失精度的。
教训:不要用浮点数作循环变量。如果一定要用浮点数做循环变量,那么步进应该足够大。
附