Golang 打印金字塔星形图案

Golang 打印金字塔星形图案

在本教程中,我们将编写一段Go语言代码来打印金字塔星形图案。我们将展示如何打印金字塔星形图案。

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

如何打印金字塔星形图案

上方显示了一个图案,在图案中,您可以清楚地看到每行增加2颗星星。图案如下:第一行1颗星星,第二行3颗星星,第三行5颗星星,以此类推。

我们将使用3个循环来打印这个图案。

示例:用Golang编写的打印金字塔星形图案的程序

语法

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 - 第一个循环从1到”row”遍历行

  • 步骤5 - 第二个循环从1到row-1遍历列,以打印星号模式

  • 步骤6 - 第三个循环从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
      *
     ***
    *****
   *******
  *********

代码描述

  • 在上面的程序中,我们首先声明了主包。

  • 我们导入了包含fmt包文件的fmt包。

  • 现在开始main()函数。

  • 接下来声明整数变量,我们将使用这些变量来打印右侧金字塔星型图案。

  • 在此代码中,第一个for循环从0到行的结束进行迭代。

  • 第二个for循环从1到row-1进行迭代,并打印空格。

  • 第三个for循环从0到(2i-1)进行迭代,并打印()星号字符。

  • 然后,我们需要在每行打印完后换行。

  • 最后使用fmt.Printf()在屏幕上打印结果。

结论

在上面的示例中,我们成功编译并执行了用于打印金字塔星型图案的Golang程序代码。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程