Swift 生成乘法表程式


本教程將討論如何編寫一個 Swift 程式來生成乘法表。

乘法表是一個指定數字的倍數列表或表格。我們可以透過將一個數字乘以整數來建立乘法表。通常,乘法表會建立到 10 倍,但您可以根據需要建立它。

以下是相同內容的演示 -

假設我們的給定輸入為 -

所需的輸出為 -

以下是 9 的乘法表

9 * 1 = 10 
9 * 2 = 20 
9 * 3 = 30 
9 * 4 = 40 
9 * 5 = 50 
9 * 6 = 60 
9 * 7 = 70 
9 * 8 = 80 
9 * 9 = 90 
9 * 10 = 100

生成乘法表的演算法

  • 步驟 1 - 定義一個變數

  • 步驟 2 - 為這些變數賦值

  • 步驟 3 - 定義另一個變數,該變數將儲存每個相乘數字的輸出並列印它們

  • 步驟 4 - 從 1 迭代到 10 的 for 迴圈,在每次迭代中,我們將 1 到 10 的數字乘以給定的輸入

  • 步驟 5 - 列印輸出

示例 1

以下程式展示瞭如何生成乘法表。

import Foundation import Glibc var value = 8 for j in 1...10{ // Here, we display the result in tabular form // Using string interpolation print("\(value) * \(j) = \(value * j)") }

輸出

8 * 1 = 8 
8 * 2 = 16 
8 * 3 = 24 
8 * 4 = 32 
8 * 5 = 40 
8 * 6 = 48 
8 * 7 = 56 
8 * 8 = 64 
8 * 9 = 72 
8 * 10 = 80

在上面的程式碼中,我們使用 for 迴圈建立了 8 的乘法表。我們已將 for 迴圈從 1 迭代到 10,並在每次迭代中,我們將 1 到 10 的數字乘以給定的輸入並顯示最終結果。

示例 2

以下程式展示瞭如何使用使用者定義的輸入生成乘法表。

import Foundation import Glibc print("Please enter the number -") // Here we convert the enter data into to integer var tablenumber = Int(readLine()!)! print("Please enter the range -") var tableRange = Int(readLine()!)! print("\nEntered number is - ", tablenumber) print("Entered range is-", tableRange) print("Following is the multiplication table is \(tablenumber)") for j in 1...tableRange{ print("\(tablenumber) * \(j) = \(tablenumber * j)") }

STDIN 輸入

Please enter the number -
19
Please enter the range -
15

輸出

Entered number is - 19
Entered range is- 15
Following is the multiplication table is 19
19 * 1 = 19
19 * 2 = 38
19 * 3 = 57
19 * 4 = 76
19 * 5 = 95
19 * 6 = 114
19 * 7 = 133
19 * 8 = 152
19 * 9 = 171
19 * 10 = 190
19 * 11 = 209
19 * 12 = 228
19 * 13 = 247
19 * 14 = 266
19 * 15 = 285

這裡我們從使用者那裡獲取兩個輸入,一個是我們要查詢乘法表的數字,另一個是範圍,我們將數字乘到該範圍,或者我們可以說乘法表的長度。現在我們從 1…迭代到使用者輸入範圍的 for 迴圈,在每次迭代中,我們將 1 到…使用者輸入範圍的數字相乘。在我們的程式碼中,輸入為 number = 19 且 range = 15,因此 for 迴圈從 1 到 15 開始並顯示 19 的表格,直到 15 的乘法。

更新於: 2022-08-01

868 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

立即開始
廣告