Go語言程式列印金字塔星型圖案


本教程將編寫一個Go語言程式碼來列印金字塔星型圖案。我們將演示如何列印金字塔星型圖案。

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

如何列印金字塔星型圖案?

上圖顯示了一個圖案,在這個圖案中,您可以清楚地看到,每增加一行,星星的數量就增加2個。圖案是這樣的:第一行1顆星,第二行3顆星,第三行5顆星,以此類推。

我們將使用3個for迴圈來列印此圖案。

示例:Go語言程式列印金字塔星型圖案

語法

For loop as a while loop in GO language:
for condition {

   // code to be executed
   // increment or decrement the count variable.
}

演算法

  • 步驟1 - 匯入fmt包

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

  • 步驟3 - 宣告並初始化整型變數(row=要列印的行數)

  • 步驟4 - 第一個for迴圈迭代行數,從1到“row”。

  • 步驟5 - 第二個for迴圈迭代列數,從1到row-1,以列印星型圖案。

  • 步驟6 - 第三個for迴圈迭代從0到(2*i-1),並列印星號。

  • 步驟7 - 列印完一行的所有列後,換行,即列印換行符。

示例

//GOLANG PROGRAM TO PRINT A PYRAMID STAR PATTERN package main // fmt package provides the function to print anything import "fmt" // calling the main function func main() { //declaring variables with integer datatype var i, j, k, row int // initializing row variable to a value to store number of rows row = 5 //print the pattern fmt.Println("\nThis is the pyramid pattern") //displaying the pattern for i = 1; i <= row; i++ { //printing the spaces for j = 1; j <= row-i; j++ { fmt.Print(" ") } //printing the stars for k = 0; k != (2*i - 1); k++ { fmt.Print("*") } // printing a new line fmt.Println() } }

輸出

This is the pyramid pattern
      *
     ***
    *****
   *******
  *********

程式碼描述

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

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

  • 現在開始main()函式

  • 接下來宣告我們將用來在Go程式碼中列印正確的金字塔星型圖案的整型變數。

  • 在這個程式碼中,第一個for迴圈從0迭代到行的末尾。

  • 第二個for迴圈從1迭代到row-1,並列印空格。

  • 第三個for迴圈從0迭代到(2*i-1),並列印(*)星號字元。

  • 然後我們需要在每一行列印完畢後換行。

  • 最後使用fmt.Printf()將結果列印到螢幕上。

結論

在上面的例子中,我們已經成功編譯並執行了Go語言程式程式碼,以列印金字塔星型圖案。

更新於:2022年11月22日

704 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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