Swift 4需要帮助才能使用(*)制作三角形 [英] Swift 4 need help to make triangle using (*)
问题描述
swift4使用星号(*)和 它需要看一棵松树,我尝试使用下面的代码,但是它没有按预期工作. 它需要看起来像等边三角形.
swift4 to make triangle tree using stars(*) and its need to look a pine tree, I tried with the below code but it is not working as expected. Its need to look like equilateral triangle.
var empty = "";
for loop1 in 1...5
{
empty = "";
for loop2 in 1...loop1
{
empty = empty + "*";
}
print (empty);
}
推荐答案
不是完全等边的,但与字符图形所能达到的程度相近.最主要的是,每行需要奇数个星号才能使居中工作,并且需要计算偏移量.
Not quite equilateral but as close as you're likely to get with character graphics. The main things are that you need an odd number of asterisks on each line for centering to work and you need to calculate an offset.
(而且,即使这样,您也需要使用等宽字体的输出才能使它看起来正确.)
(And, even so, you need output in a monospaced font for this to look right.)
为便于阅读进行了一些清理(并结合了第一个注释中的更改).
Some cleanup for readability (and incorporating the change from the first comment).
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)
}
这篇关于Swift 4需要帮助才能使用(*)制作三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!