各位大大,请问如何在 ruby 中指定精度来进行迭代小数呢?
#6 楼 @fresh_fish (1..10).step(0.1){|i| print i,""} 请问这样的输出结果为什么是
1.01.11.21.31.41.51.61.71.81.90000000000000012.02.12.22.30000000000000032.42.52.62.72.80000000000000032.93.03.13.23.30000000000000033.40000000000000043.53.63.73.80000000000000033.90000000000000044.04.10000000000000054.24.34.44.54.60000000000000054.74.84.95.05.10000000000000055.25.35.45.55.60000000000000055.75.8000000000000015.96.06.10000000000000056.26.3000000000000016.46.56.60000000000000056.76.8000000000000016.97.07.10000000000000057.27.3000000000000017.47.57.60000000000000057.77.8000000000000017.98.08.18.2000000000000018.38.48.58.68.7000000000000018.88.99.09.19.2000000000000019.39.49.59.69.7000000000000019.89.910.0=> 1..10
irb(main):003:0> (1..10).step(0.1){|i| print i,' '}
1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.0 3.1
3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4.0 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5.0 5.1 5.2 5.3
5.4 5.5 5.6 5.7 5.8 5.9 6.0 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7.0 7.1 7.2 7.3 7.4 7.5
7.6 7.7 7.8 7.9 8.0 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 9.0 9.1 9.2 9.3 9.4 9.5 9.6 9.7
9.8 9.9 10.0 => 1..10
irb(main):004:0> RUBY_VERSION
=> "1.8.7"
irb(main):001:0> (1..10).step(0.1){|i| print i,' '} 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9000000000000001 2.0 2.1 2.2 2.3000000000000003 2.4 2.5 2.6 2.7 2.8000000000000003 2.9 3.0 3.1 3.2 3.3000000000000003 3.4000000000000004 3.5 3.6 3.7 3.8000000000000003 3.9000000000000004 4.0 4.1000000000000005 4.2 4.3 4.4 4.5 4.6000000000000005 4.7 4.8 4.9 5.0 5.1000000000000005 5.2 5.3 5.4 5.5 5.6000000000000005 5.7 5.800000000000001 5.9 6.0 6.1000000000000005 6.2 6.300000000000001 6.4 6.5 6.6000000000000005 6.7 6.800000000000001 6.9 7.0 7.1000000000000005 7.2 7.300000000000001 7.4 7.5 7.6000000000000005 7.7 7.800000000000001 7.9 8.0 8.1 8.200000000000001 8.3 8.4 8.5 8.6 8.700000000000001 8.8 8.9 9.0 9.1 9.200000000000001 9.3 9.4 9.5 9.6 9.700000000000001 9.8 9.9 10.0 => 1..10
irb(main):005:0> RUBY_VERSION => "1.9.2"
(1..24).step(0.5).to_a
1.step(by:0.5, to:24).to_a
或者 1.step(to:24, by:0.5).to_a
1.step(24, 0.5).to_a
可是不能使用1.step(0.5, 24).to_a