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()将结果打印到屏幕上。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
结论
在上面的例子中,我们已经成功编译并执行了Go语言程序代码,以打印金字塔星型图案。
广告