double opacity = 0; for (int i = 0; i < 100; i++) { opacity = ((int) (opacity * 100 + 1)) / 100.0; System.out.println("opacity=" + opacity); }
opacity=0.01
opacity=0.02
opacity=0.03
opacity=0.04
opacity=0.05
opacity=0.06
(中間省略……)
opacity=0.27
opacity=0.28
opacity=0.29
opacity=0.29
opacity=0.29
……後面一直爲0.29html
如今我把上面那個程序作一點修改:git
double opacity = 0; for (int i = 0; i < 100; i++) { opacity = ((int) (opacity * 100 + 1)) / 100.0; System.out.println("opacity=" + new BigDecimal(opacity)); System.out.println("opacity*100=" + new BigDecimal(opacity * 100)); System.out.println("----------------------------"); }
opacity=0.01000000000000000020816681711721685132943093776702880859375opacity*100=1----------------------------opacity=0.0200000000000000004163336342344337026588618755340576171875opacity*100=2----------------------------opacity=0.0299999999999999988897769753748434595763683319091796875opacity*100=3(中間省略……)opacity=0.270000000000000017763568394002504646778106689453125opacity*100=27----------------------------opacity=0.2800000000000000266453525910037569701671600341796875opacity*100=28.000000000000003552713678800500929355621337890625----------------------------opacity=0.289999999999999980015985556747182272374629974365234375opacity*100=28.999999999999996447286321199499070644378662109375……後面一直重複相同的內容
程序的目的是讓opacity的值每次增長0.01,那麼就只須要每次加上0.01就行了,徹底不須要繞圈子。以下:程序員
double opacity = 0; while (opacity < 1) { opacity += 0.01; System.out.println("opacity=" + opacity); }
opacity=0.01
opacity=0.02
opacity=0.03
opacity=0.04
opacity=0.05
opacity=0.060000000000000005
(中間省略……)
opacity=0.9800000000000006
opacity=0.9900000000000007
opacity=1.0000000000000007github
double opacity = 0; for (int i = 0; i < 100; i++) { opacity = ((int) (opacity * 100 + 1.5)) / 100.0; System.out.println("opacity=" + opacity); }
opacity=0.01
opacity=0.02
opacity=0.03
opacity=0.04
opacity=0.05
opacity=0.06
(中間省略……)
opacity=0.96
opacity=0.97
opacity=0.98
opacity=0.99
opacity=1.0小程序