尝试使用while循环在Swift中制作一个星号三角形

时间:2019-04-23 23:32:43

标签: swift while-loop

我正在尝试在Swift中输出棕褐色星号三角形。我必须使用while循环。

我已经尝试过自行循环-不走运 我想我需要将一个while循环和一个for循环嵌套在一起,但是甚至不确定我能做到这一点。否则我可能会使这种方式变得比所需的困难:)。编程的超级新手...我根本不知道如何在while循环中添加“ *”。下面是我尝试过的最新代码,但是这是错误的(显然)任何帮助都将得到赞赏

        let rows = 5
        for i in 1...rows{
            for j in 1...i{
                print("\(j) ", terminator: "")
            }
            var num_stars = 1


            while num_stars <= 5{
                print(num_stars)
                num_stars += 1

            }
              print("")

    }

1 个答案:

答案 0 :(得分:1)

简单地:

let rows = 5
var i = 1
while i <= rows {
    print(String(repeating: "*", count: i))
    i += 1
}

输出:

*
**
***
****
*****

这对我来说看起来更漂亮:

let rows = 5
var i = 0
while i < rows {
    let spaces = String(repeating: " ", count: rows - i - 1)
    let stars = String(repeating: "*", count: 2 * i + 1)
    print(spaces + stars)
    i += 1
}
    *
   ***
  *****
 *******
*********

或:

while i < rows {
    let spaces = String(repeating: " ", count: rows - i - 1)
    print(spaces, terminator: "")
    if i > 0 {
        print("*", terminator: "")
        if i < rows - 1 {
            let insideTriangleSpaces = String(repeating: " ", count: 2 * (i - 1) + 1)
            print(insideTriangleSpaces, terminator: "")
        } else {
            let insideTriangleStars = String(repeating: "*", count: 2 * (i - 1) + 1)
            print(insideTriangleStars, terminator: "")
        }
    }
    print("*")
    i += 1
}
    *
   * *
  *   *
 *     *
*********