Golang 打印星形帕斯卡三角形
在本教程中,我们将学习如何使用Go编程语言打印星形帕斯卡三角形。
示例1:使用strconv包打印星形帕斯卡三角形的Golang代码
语法
func Itoa(x int) string
Itoa() 函数接受一个整数参数,并在基数为10时返回x的字符串表示形式
步骤
- 第一步 - 导入fmt和strconv包。
-
第二步 - 开始函数 main() 。
-
第三步 - 声明并初始化变量。
-
第四步 - 使用带有条件和增量的循环。
-
第五步 - 使用 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 变量初始化为您想要的 Pascal 三角形模式的整数值。使用 fmt.Scanln() 读取并存储 rows 的值。
-
使用 for 循环:条件放在 if 语句内部,并在条件满足时停止执行。
-
在代码的第 28 行:循环从 i = 0 开始执行,直到 i<rows 的条件为真,并且后置语句是 i++。
-
在代码的第 32 行:它在第二个循环中执行 for (j=0; j<=i; j++)。
-
在此循环中调用函数 strconv.Itoa() 计算 Pascal 三角形。
-
最后使用 fmt.Println 以三角形的形式在屏幕上打印结果。
结论
我们已经成功编译并执行了上述示例中打印星形 Pascal 三角形的 Golang 程序代码。