Swift 程式設計列印數字左三角形圖案
本教程將討論如何編寫 Swift 程式來列印數字的左三角形圖案。
數字圖案是一系列數字,用於開發不同的圖案或形狀,例如金字塔、矩形、十字架等。這些數字圖案通常用於理解或練習程式流程控制,它們也對邏輯思維很有幫助。
要建立數字的左三角形圖案,我們可以使用以下任何方法:
使用巢狀 for 迴圈
使用 init() 函式
使用 stride 函式
以下是演示:
輸入
假設我們的給定輸入是:
Num = 10
輸出
期望的輸出將是:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10
方法 1 - 使用巢狀 for 迴圈
我們可以使用巢狀 for 迴圈建立左三角形星型圖案或任何其他圖案。
示例
下面的程式演示瞭如何使用巢狀 for 迴圈列印數字的左三角形圖案。
import Foundation import Glibc // Size of the left triangle pattern of numbers let num = 9 // Handle the length of pattern for x in 1...num{ // Printing left triangle pattern of numbers for y in 1...x{ print(y, terminator : " ") } // New line after each row print(" ") }
輸出
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9
在上面的程式碼中,我們使用巢狀 for 迴圈來列印數字的左三角形圖案。最外層的 for 迴圈(從 1 到 9)用於處理要列印的行數,每一行都以換行符開頭。現在,巢狀的 for 迴圈(從 1 到 x)用於以三角形圖案列印數字 1 到 9,或者我們可以說它用於處理圖案中的列數。
方法 2 - 使用 init() 函式
Swift 提供一個名為 String.init() 的內建函式。使用此函式,我們可以建立任何圖案。String.init() 函式建立一個字串,其中給定字元重複指定次數。
語法
以下是語法:
String.init(repeating:Character, count: Int)
這裡,repeating 表示此方法重複的字元,count 表示給定字元在結果字串中重複的總次數。
示例
下面的程式演示瞭如何使用 String.init() 函式列印數字的左三角形圖案。
import Foundation import Glibc // Size of the left triangle pattern of numbers let num = 4 // Handle the length of pattern for i in 1...num{ // Printing left triangle pattern of numbers print(String.init(repeating:"123", count:i)) }
輸出
123 123123 123123123 123123123123
在上面的程式碼中,我們使用 String.init() 函式建立了一個高度為 4 的數字字串“123”的左三角形圖案。我們使用 for 迴圈(從 1 到 num),用於列印每一行。在此迴圈中,我們使用 String.init() 函式。此函式根據 count 值(即 i)列印“123”:
print(String.init(repeating:"123", count:i))
因此,上述程式碼的工作原理是:
num = 4
在第一次迭代中:i = 1
print(String.init(repeating: "123”, count: 1))
因此它列印一次“123”
print(String.init(repeating: "123”, count: 2))
因此它列印兩次“123”
以此類推,直到第四次迭代,並列印數字的左三角形圖案。
方法 3 - 使用 stride 函式
Swift 提供一個名為 stride() 的內建函式。stride() 函式用於以增量或減量從一個值移動到另一個值。或者我們可以說 stride() 函式返回從起始值開始但不包括結束值的序列,並且給定序列中的每個值都按給定量遞增。
語法
以下是語法:
stride(from:startValue, to: endValue, by:count)
這裡:
from - 表示用於給定序列的起始值。
to - 表示限制給定序列的結束值
by - 表示每次迭代的步長,正值表示向上迭代或增量,負值表示向下迭代或減量。
示例
下面的程式演示瞭如何使用 stride() 函式列印數字的左三角形圖案。
import Foundation import Glibc // Size of the left triangle pattern of numbers let num = 13 // Handle the length of pattern for i in 1...num{ // Printing left triangle pattern of numbers // Using stride() function for j in stride(from: 1, to: i, by: 1){ print(j, terminator:" ") } print("") }
輸出
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 11 12
在上面的程式碼中,我們使用巢狀 for 迴圈以及 stride() 函式。最外層的 for 迴圈(從 1 到 num)用於處理要列印的行數,每一行都以換行符開頭。巢狀的 for 迴圈用於使用 stride() 函式列印數字的左三角形圖案:
for _ in stride(from: 1, to: i, by: 1) { print("*", terminator:" ") }
這裡迭代從 1 開始到 i,每次迭代增加 1,並以左三角形圖案列印數字 1 到 12。