Go 語言程式列印楊輝三角形
在本教程中,我們將學習如何使用 Go 程式語言列印星號楊輝三角形。
示例 1:使用 Strconv 包的 Go 程式碼列印星號楊輝三角形
語法
func Itoa(x int) string
Itoa() 函式接收一個整數引數,並在基數為 10 時返回 x 的字串表示形式。
演算法
步驟 1 - 匯入 fmt 包和 strconv 包。
步驟 2 - 啟動函式 main ()。
步驟 3 - 宣告並初始化變數。
步驟 4 - 使用帶有條件和增量的 for 迴圈。
步驟 5 - 使用fmt.Println ()列印結果。
示例
// GOLANG PROGRAM TO PRINT STAR PASCALS TRIANGLE package main // fmt package provides the function to print anything // Package strconv implements conversions to and from // string representations of basic data types import ( "fmt" "strconv" ) // start function main () func main() { // declare the variables var i, j, rows, num int // initialize the rows variable rows = 7 // Scanln() function scans the input, reads and stores //the successive space-separated values into successive arguments fmt.Scanln(&rows) fmt.Println("GOLANG PROGRAM TO PRINT STAR PASCALS TRIANGLE") // Use of For Loop // This loop starts when i = 0 // executes till i<rows condition is true // post statement is i++ for i = 0; i < rows; i++ { num = 1 fmt.Printf("%"+strconv.Itoa((rows-i)*2)+"s", "") // run next loop as for (j=0; j<=i; j++) for j = 0; j <= i; j++ { fmt.Printf("%4d", num) num = num * (i - j) / (j + 1) } fmt.Println() // print the result } }
輸出
GOLANG PROGRAM TO PRINT STAR PASCALS TRIANGLE 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1
程式碼描述
在上面的程式中,我們首先宣告包 main。
我們匯入了包含 fmt 包檔案的 fmt 包。我們還匯入了包 strconv,它實現了對基本資料型別字串表示形式的轉換。
現在開始函式main()。
宣告四個整數變數 i、j、num 和 rows。將 rows 變數初始化為您想要的楊輝三角形圖案的整數值。使用fmt.Scanln()讀取並存儲 rows 值。
使用 for 迴圈:條件在 if 語句中給出,並在條件正確時停止執行。
在程式碼的第 28 行:當 i = 0 時迴圈開始執行,直到 i<rows 條件為真,後置語句為 i++。
在程式碼的第 32 行:它執行下一個迴圈,如 for (j=0; j<=i; j++)。
在此迴圈中,呼叫函式strconv.Itoa()計算楊輝三角形。
最後,使用fmt.Println以三角形形式在螢幕上列印結果。
結論
在上面的示例中,我們已成功編譯並執行了 Go 語言程式程式碼以列印星號楊輝三角形。
廣告