Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

for loop - Swift 4 need help to make triangle using (*)

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);
}

Now, Expected

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)

Edit: 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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...