我要迭代14次,并每次向x
添加2.50,因此变量更改为:
i = 0, x = 5.5
i = 1, x = 8
i = 2, x = 10.5
i = 3, x = 13
...
我做到了:
base_times = 14
base_times.times do |i|
x = 3
x = x + 2.50
puts "#{x}"
end
答案 0 :(得分:0)
由于范围可变,您应该将x定义移出:
base_times=14
x=3
base_times.times do |i|
x += 2.50
puts "#{x}"
end
还有x = x +
,+=
的语法糖。
答案 1 :(得分:0)
start = 3
increment = 2.5
base_times = 6
enum = (start+increment).step(by: increment)
base_times.times { puts enum.next }
打印
3.0
5.5
8.0
10.5
13.0
15.5
请参见Numeric#step。