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

Categories

0 votes
625 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...