此ruby代码生成金字塔:
w = 20
1.upto(w) { |i| puts ">"+" "*(w-i)+"."*i*2+" "*(w-i)+"<" }
像这样:
> .. <
> .... <
> ...... <
> ........ <
> .......... <
> ............ <
> .............. <
> ................ <
> .................. <
> .................... <
> ...................... <
> ........................ <
> .......................... <
> ............................ <
> .............................. <
> ................................ <
> .................................. <
> .................................... <
> ...................................... <
>........................................<
我想让金字塔顶部有一个点而不是两个(目前因为"."*i*2
使其对称)。
我怎样才能做到这一点?
答案 0 :(得分:2)
w=20; 1.upto(w) { |i| puts ">"+" "*(w-i)+"."*(i*2-1)+" "*(w-i)+"<" }
答案 1 :(得分:1)
您使用的是固定宽度的字体,因此无法将句点置于当前金字塔之上。你需要使用奇数个点而不是偶数:
w = 20
1.upto(w) do |i|
spaces = " " * (w-i)
dots = "." * (i*2 - 1) # Use one fewer dot per line, starting with one dot
puts ">" + spaces + dots + spaces + "<"
end
这会产生:
> . <
> ... <
> ..... <
> ....... <
> ......... <
> ........... <
> ............. <
> ............... <
> ................. <
> ................... <
> ..................... <
> ....................... <
> ......................... <
> ........................... <
> ............................. <
> ............................... <
> ................................. <
> ................................... <
> ..................................... <
>.......................................<
答案 2 :(得分:1)
使用times
会使其更清晰。此外,还有center
简化了事情:
20.times{|i| puts ">#{("."*(i*2+1)).center(39)}<"}
答案 3 :(得分:0)
S, W = ' ', 20; 1.upto(W) {|i| n = W - i; puts ">#{S*n + '.' * (2*i - 1) + S*n}<"}