如何在Go语言中打印右对齐的星型图案

huangapple go评论76阅读模式
英文:

How to print the star pattern aligned to right hand side in GO lang

问题

我想在GO语言中打印一个星星图案。期望的输出如下所示:

如何在Go语言中打印右对齐的星型图案

我写了一个程序来打印它,但是我无法将输出对齐在最左边。

代码如下:

package main

import "fmt"

func main() {
    for i := 1; i <= 6; i++ {
        if i == 1 {
            fmt.Printfln("#")
            fmt.Println()
        }
        if i == 2 {
            fmt.Println("##")
            fmt.Println()
        }
        if i == 3 {
            fmt.Println("###")
            fmt.Println()
        }
        if i == 4 {
            fmt.Println("####")
            fmt.Println()
        }
        if i == 5 {
            fmt.Println("#####")
            fmt.Println()
        }
        if i == 6 {
            fmt.Println("######")
            fmt.Println()
        }
    }

    //在这里输入你的代码。从标准输入读取输入,将输出打印到标准输出
}

我得到的输出是:

如何在Go语言中打印右对齐的星型图案

我该如何在GO语言中实现期望的格式?

英文:

I want to print a star pattern in GO .The desired output is as belows :

如何在Go语言中打印右对齐的星型图案

I wrote the program to print it but I could write it to print the output aliged on the leftmost side.

The code is :

package main

import &quot;fmt&quot;

func main() {
	for i := 1; i &lt;= 6; i++ {
		if i == 1 {
			fmt.Printfln(&quot;#&quot;)
			fmt.Println()
		}
		if i == 2 {
			fmt.Println( &quot;##&quot;)
			fmt.Println()
		}
		if i == 3 {
			fmt.Println(&quot;###&quot;)
			fmt.Println()
		}
		if i == 4 {
			fmt.Println(&quot;####&quot;)
			fmt.Println()
		}
		if i == 5 {
			fmt.Println(&quot;#####&quot;)
			fmt.Println()
		}
		if i == 6 {
			fmt.Println(&quot;######&quot;)
			fmt.Println()
		}
	}

	//Enter your code here. Read input from STDIN. Print output to STDOUT
}

The output that I get is :
如何在Go语言中打印右对齐的星型图案

How can I achieve the desired format in GO ?

答案1

得分: 3

package main

import (
	"fmt"
	"strings"
)

func main() {
	for i := 1; i <= 6; i++ {
		fmt.Printf("%6s\n", strings.Repeat("#", i))
	}
}

在<kbd>Go playground</kbd>上尝试一下吧。

英文:
package main

import (
	&quot;fmt&quot;
	&quot;strings&quot;
)

func main() {
	for i := 1; i &lt;= 6; i++ {
		fmt.Printf(&quot;%6s\n&quot;, strings.Repeat(&quot;#&quot;, i))
	}
}

Try it on the <kbd>Go playground</kbd>

huangapple
  • 本文由 发表于 2015年10月13日 07:47:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/33091939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定