Golang程序 打印帕斯卡尔星形三角形

Golang程序 打印帕斯卡尔星形三角形

在本教程中,我们将学习如何使用Go编程语言来打印帕斯卡星形三角形。

例1:使用Strconv包打印Star Pascal三角形的Golang代码

语法

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变量初始化为你想要的Pascal三角模式的整数值。使用 fmt.Scanln() 读取并存储 rows 的值。

  • 使用for循环。条件是在if语句中给出的,一旦条件正确,就会提到停止执行。

  • 在代码的第28行。循环从i = 0开始,一直执行到i<rows条件为真,后置语句为i++。

  • 在代码的第32行:它运行下一个循环为for(j=0; j<=i; j++)。

  • 在这个循环中,函数 strconv.Itoa() 被调用来计算帕斯卡的三角形。

  • 最后使用 fmt.Println 将结果以三角形的形式打印在屏幕上 。

总结

我们已经成功地编译并执行了Golang程序代码来打印上述例子中的帕斯卡三角形。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程