swift4使用星号制作三角树(*)并且需要看一棵松树,我尝试使用下面的代码,但它没有按预期工作。它需要看起来像等边三角形。
var empty = "";
for loop1 in 1...5
{
empty = "";
for loop2 in 1...loop1
{
empty = empty + "*";
}
print (empty);
}
不是等边的,但是尽可能接近你的角色图形。主要的是你需要在每一行上使用奇数个星号来居中工作,你需要计算一个偏移量。
(即便如此,你需要用等宽字体输出才能看起来正确。)
编辑:为了便于阅读而进行一些清理(并纳入第一条评论的更改)。
let treeHeight = 5
let treeWidth = treeHeight * 2 - 1
for lineNumber in 1...treeHeight {
// How many asterisks to print
let stars = 2 * lineNumber - 1
var line = ""
// Half the non-star space
let spaces = (treeWidth - stars) / 2
if spaces > 0 {
line = String(repeating: " ", count: spaces)
}
line += String(repeating: "*", count: stars)
print (line)
}
您可以使用此代码打印星形三角形
for i in 1...5{
for _ in 1...i{
print("*",terminator:"")
}
print(" ")
}