IT Notes‎ > ‎Java‎ > ‎Java Language‎ > ‎《Java 解惑》笔记‎ > ‎

Puzzle 34: Down for the Court


本问题用到代码如下:
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都会丢失精度的。

教训:不要用浮点数作循环变量。如果一定要用浮点数做循环变量,那么步进因该足够大。



  1. Puzzle 26: In the Loop
  2. Puzzle 27: Shifty i's
  3. Puzzle 28: Looper
  4. Puzzle 31: Ghost of Looper
  5. JLS 5.1.2 Widening Primitive Conversion
  6. JLS 15.20.1 Numerical Comparison Operators <, <=, >, and >=
Comments