Swift 程式設計列印實心矩形星形圖案
本教程將討論如何編寫 Swift 程式來列印實心矩形星形圖案。
星形圖案是由“*”組成的序列,用於開發不同的圖案或形狀,如金字塔、矩形、十字形等。這些星形圖案通常用於理解或練習程式流程控制,它們也有利於邏輯思維的培養。
要建立實心矩形星形圖案,我們可以使用以下方法之一:
使用巢狀 for 迴圈
使用 init() 函式
使用 stride 函式
下面是演示:
輸入
假設我們的給定輸入是:
Length = 7 Width = 5
輸出
期望的輸出將是:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
方法 1 - 使用巢狀 For 迴圈
我們可以使用巢狀 for 迴圈建立實心矩形星形圖案或任何其他圖案。這裡每個 for 迴圈處理不同的任務,例如最外層的 for 迴圈用於新行,巢狀的 for 迴圈用於在列中列印“*”。
示例
以下程式演示瞭如何使用巢狀 for 迴圈列印實心矩形星形圖案。
import Foundation import Glibc // Length and width of solid rectangle // star pattern let length = 8 let width = 3 // Handle the width of the pattern for _ in 1...width{ // Handle the length of the pattern for _ in 1...length{ print("*", terminator : " ") } // New line after each row print(" ") }
輸出
* * * * * * * * * * * * * * * * * * * * * * * *
在這裡,在上面的程式碼中,我們有 length = 8 和 width = 3。現在我們使用巢狀 for 迴圈來列印實心矩形星形圖案。最外層的 for 迴圈(從 1 到 3)用於處理要列印的行數,並且每一行都以新行開頭。現在巢狀的 for 迴圈(從 1 到 8)用於處理實心矩形星形圖案中要列印的列數,使用“*”。
方法 2 - 使用 init() 函式
Swift 提供了一個名為 String.init() 的內建函式。使用此函式,我們可以建立任何圖案。String.init() 函式建立一個字串,其中給定字元重複指定次數。
語法
以下是語法:
String.init(repeating:Character, count: Int)
這裡,repeating 表示此方法重複的字元,count 表示給定字元在結果字串中重複的總次數。
示例
以下程式演示瞭如何使用 string.init() 函式列印實心矩形星形圖案。
import Foundation import Glibc // Length and width of solid rectangle // star pattern let length = 8 let width = 4 // Handle the length of pattern for _ in 1...width{ // Printing solid rectangle star pattern print(String.init(repeating: "*", count: width) + String.init(repeating:"*", count:length-width)) }
輸出
******** ******** ******** ********
在這裡,在上面的程式碼中,我們有 length = 8 和 width = 3。現在使用 String.init() 函式,我們建立了一個實心矩形星形圖案。這裡我們使用 for 迴圈(從 1 到 4),用於列印每一行。在此迴圈中,我們使用 String.init() 函式列印實心矩形星形圖案:
String.init(repeating: "*", count: width)
根據 count 的值(即 length-width)列印“*”行,以及
String.init(repeating:"*", count:length-width)
根據 count 的值(即 length-width)列印“*”列
方法 3 - 使用 stride 函式
Swift 提供了一個名為 stride() 的內建函式。stride() 函式用於以增量或減量從一個值移動到另一個值。或者我們可以說 stride() 函式返回從起始值開始的序列,但不包括結束值,並且給定序列中的每個值都以給定量遞增。
語法
以下是語法:
stride(from:startValue, to: endValue, by:count)
這裡,
from − 表示要用於給定序列的起始值。
to − 表示限制給定序列的結束值
by − 表示每次迭代的步長,這裡正值表示向上迭代或增量,負值表示向下迭代或減量。
示例
以下程式演示瞭如何使用 stride() 函式列印實心矩形星形圖案。
import Foundation import Glibc // Length and width of solid rectangle // star pattern let length = 10 let width = 6 // Handle the length of pattern for _ in 1...width{ // Printing solid rectangle star pattern // Using stride() function for _ in stride(from: 1, to: length, by: 1){ print("*", terminator:" ") } print("") }
輸出
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
在這裡,在上面的程式碼中,我們有 length = 10 和 width = 6。現在我們使用巢狀 for 迴圈。最外層的 for 迴圈(從 1 到 6)用於處理要列印的行數,並且每一行都以新行開頭。巢狀的 for 迴圈用於使用 stride() 函式列印實心矩形星形圖案:
for _ in stride(from: 1, to: length, by: 1) { print("*", terminator:" ") }
這裡的迭代從 1 到 length(即 10)開始,每次迭代增加 1,並在實心矩形圖案中列印“*”。