longとfloatの足し算の落とし穴
longとfloatの足し算を行なうと精度が落ちるので注意が必要だ。
コンパイラが警告してくれてもいいのに。
public class Test { public static void main(String[] args) throws Exception { System.out.println("1000000000000L + 1 - 1000000000000L = " + (1000000000000L + 1 - 1000000000000L)); System.out.println("1000000000000L + 1 = " + (1000000000000L + 1)); System.out.println("1000000000000L + 1f - 1000000000000L = " + (1000000000000L + 1f - 1000000000000L)); System.out.println("1000000000000L + 1f = " + (1000000000000L + 1f)); System.out.println("1000000000000L + 1d - 1000000000000L = " + (1000000000000L + 1d - 1000000000000L)); System.out.println("1000000000000L + 1d = " + (1000000000000L + 1d)); System.out.println("1000000000000L + 1L - 1000000000000L = " + (1000000000000L + 1L - 1000000000000L)); System.out.println("1000000000000L + 1L = " + (1000000000000L + 1L)); } }
結果
1000000000000L + 1 - 1000000000000L = 1
1000000000000L + 1 = 1000000000001
1000000000000L + 1f - 1000000000000L = 0.0
1000000000000L + 1f = 1.0E12
1000000000000L + 1d - 1000000000000L = 1.0
1000000000000L + 1d = 1.000000000001E12
1000000000000L + 1L - 1000000000000L = 1
1000000000000L + 1L = 1000000000001