"hello"
仅由puts
打印三次。应该打印六次,不是吗?
i = 0
j = 0
while(i != 2)
while(j != 3)
puts "hello"
j += 1
end
i += 1
end
答案 0 :(得分:1)
您必须在内部j
循环之外将0
设置为while
。
i = 0
j = 0
while(i != 2)
while(j != 3)
puts "hello"
j += 1
end
# this is needed, as inside the upper loop, you made j to 3 after 3 iteration.
# thus you need to reset it to 0 again, to start again 3 times iteration.
j = 0
i += 1
end
# >> hello
# >> hello
# >> hello
# >> hello
# >> hello
# >> hello
更好的是 -
i = 0
while(i != 2)
j = 0
while(j != 3)
puts "hello"
j += 1
end
i += 1
end
答案 1 :(得分:0)
如果你使用循环{},你可能会更容易 - 即使你必须自己跟踪计数器,我发现它比使用while或xxtimes更容易理解,也可以正常工作。