Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...