Go語言程式列印反向金字塔星形圖案
在本教程中,我們將編寫一段 Go 語言程式碼來列印反向金字塔星形圖案。我們將演示如何列印反向金字塔星形圖案。
*********
*******
*****
***
*
如何列印反向金字塔星形圖案?
上面顯示了一個圖案,在這個圖案中,您可以清楚地看到,每行增加,星星的數量減少 2 個。如果總行數為 5,則圖案如下:第一行 9 個星,第二行 7 個星,第三行 5 個星,依此類推,逐漸減少。
我們將使用 4 個迴圈來列印此圖案。
Go語言程式列印反向金字塔星形圖案
語法
for [condition | ( init; condition; increment) | Range] {
statement(s);
}
演算法
步驟 1 - 匯入 fmt 包
步驟 2 - 開始 main() 函式
步驟 3 - 宣告並初始化整型變數(row= 要列印的行數)
步驟 4 - 使用不同的 for 迴圈來列印反向金字塔星形圖案。
步驟 5 - 列印完一行中的所有列後,換行,即列印新行。
示例
//GOLANG PROGRAM TO PRINT REVERSE PYRAMID STAR PATTERN package main // fmt package provides the function to print anything import "fmt"//this is the main function func main() { //initialize the number of rows to print var rows = 5 //declaring variables with integer datatype fmt.Println("\nThis is the Reverse pyramid pattern") var i, j int //displaying the pattern for i = rows; i >= 1; i-- { //printing the spaces for space := 1; space <= rows-i; space++ { fmt.Print(" ") } //printing the stars for j = i; j <= 2*i-1; j++ { fmt.Printf("*") } for j = 0; j < i-1; j++ { fmt.Printf("*") } fmt.Println("") } }
輸出
This is the pyramid pattern
*********
*******
*****
***
*
程式碼描述
在上面的程式中,我們首先宣告 main 包。
我們匯入了 fmt 包,其中包含 fmt 包的檔案
現在開始 main() 函式
接下來宣告我們將在 Go 程式碼中用來列印正確的金字塔星形圖案的整型變數。
我們使用了不同的 for 迴圈,為了列印空格和星號,從而列印反向金字塔星形圖案。
在每行圖案之後換行。
最後使用 fmt.Printf() 將結果列印到螢幕上。
結論
在上面的示例中,我們成功地解釋並執行了 Go 語言程式程式碼,以列印反向金字塔星形圖案。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP