Go語言程式:顯示數字的因子


在本教程程式中,我們將學習如何在Go程式語言中顯示給定數字的因子。

數字的因子定義為能夠整除該數字的代數表示式,餘數為零。所有合數都將有兩個以上的因子,包括1和該數字本身。

例如:3乘以7等於21。我們說3和7是21的因子。

以下是相同的演示 -

輸入

Suppose our input is = 15

輸出

The factors of 15 are: 1 3 5 15

語法

For loop syntax:
for initialization; condition; update {
   statement(s)
}

示例-1:展示如何在Golang程式的main()函式內顯示數字的因子

以下是本Go程式程式碼中使用的步驟。

演算法

  • 步驟1 - 匯入fmt包

  • 步驟2 - 開始main()函式

  • 步驟3 - 宣告並初始化變數

  • 步驟4 - 使用for迴圈顯示因子,條件為num%i == 0

  • 步驟5 - for迴圈從i=0迭代到i<=num

  • 步驟6 - 使用fmt.Println()列印結果

示例

package main
// fmt package provides the function to print anything
import "fmt"

// start the main() function
func main() {
   // Declare and initialize the variables
   var num = 15
   var i int
    
   fmt.Println("The factors of the number", num, " are = ")
   // using for loop the condition is evaluated. 
   // If the condition is true, the body of the for loop is executed
   for i = 1; i <= num; i++ {
      if num%i == 0 {
         fmt.Println(i)
      }
   } // Print the result
}

輸出

The factors of the number 15 are = 
1
3
5
15

程式碼描述

  • 在上面的程式中,我們首先宣告main包。

  • 我們匯入了包含fmt包檔案的fmt包。

  • 現在開始main()函式。

  • 宣告並初始化整數變數num和i。

  • 使用for迴圈評估條件。

  • 在程式中,“for”迴圈迭代直到i為假。變數i是for迴圈中的索引變數。在每次迭代步驟中,都會檢查num是否被i整除。這是i作為num因子的條件。然後變數i的值加1。

  • 最後,我們使用內建函式fmt.Println()列印結果,數字的因子將顯示在螢幕上。

示例-2:展示如何在Golang程式的兩個單獨函式中顯示數字的因子

以下是本Go程式程式碼中使用的步驟。

演算法

  • 步驟1 - 匯入fmt包。

  • 步驟2 - 在main()函式之外建立一個factor()函式。

  • 步驟3 - 宣告變數i。

  • 步驟4 - 使用帶條件的for迴圈。

  • 步驟5 - 開始main()函式。

  • 步驟6 - 呼叫factor()函式來查詢給定數字的因子。

  • 步驟7 - 使用fmt.Println()列印結果。

示例

package main
// fmt package provides the function to print anything
import "fmt"

// create a function factor() to find the factors of a number
func factor(a int) int {

   // declare and initialize the variable
   var i int
   // using for loop the condition is evaluated
   // If the condition is true, the body of the for loop is executed
   for i = 1; i <= a; i++ {
      if a%i == 0 {
         fmt.Println(i)
      }
   }
return 0
}
// Start the main() function
func main() {
   fmt.Println("The factors of the number 6 are")

   // calling the function factor() to find factor of a given number
   factor(6) 
   
   // Print the result
}

輸出

The factors of the number are
1
2
3
6

程式碼描述

  • 在上面的程式中,我們首先宣告main包。

  • 我們匯入了包含fmt包檔案的fmt包。

  • 我們在main()函式之外建立了一個factor()函式來查詢給定數字的因子。

  • 我們聲明瞭整數變數a和i,變數i是for迴圈中的索引變數。

  • 在程式中,使用for迴圈評估條件。“for”迴圈迭代直到i為假。在每次迭代步驟中,都會檢查“a”是否被i整除。這是i作為“a”因子的條件。然後變數i的值加1。

  • 接下來,我們開始main()函式。

  • 現在我們呼叫factor()函式來查詢給定數字的因子。

  • 結果使用內建函式fmt.Println()列印,數字的因子將顯示在螢幕上。

結論

在以上兩個示例中,我們已成功編譯並執行了Golang程式碼以顯示數字的因子。

在上述程式設計程式碼中,“for”迴圈用於重複執行程式碼塊,直到滿足指定的條件。我們使用內建函式fmt.Println()函式在輸出螢幕上列印結果。在以上示例中,我們展示瞭如何在Go程式語言中實現迴圈語句。

更新於:2022年12月29日

瀏覽量:705

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.