使用for循环打印给定的字符模式。

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

Printing the given pattern of characters using for loops?

问题

我正在做一个关于Go语言的练习,要求我打印如下的字母图案:

G
GG
GGG
GGGG
GGGGG

要求打印25行,每行增加一个字母。

我被要求使用一个for循环解决这个问题,然后再使用两个for循环解决。我已经解决了这两个问题,但是尽管我使用两个for循环的代码输出结果正确,但我觉得它有些奇怪,不太好:

func manyG2() {
    var counter string
    for i := 0; i <= 24; i++ {
        for x := 0; x == 0; x++ {
            counter += "G"
            fmt.Println(counter)
        }
    }
}

还有其他的方式可以使用两个for循环来编写吗?

英文:

I'm doing an exercise on Go that asks me to print a letter like this

G
GG
GGG
GGGG
GGGGG

for 25 different lines, and adding one more letter each time.

I'm asked to solve it one time using only one for loop, and then again but with two for loops. I already solved both, but even though my code using two for loops works gives the right output, I think it's weird and not ok:

func manyG2() {
	var counter string
	for i := 0; i &lt;= 24; i++ {
		for x := 0; x == 0; x++ {
			counter += &quot;G&quot;
			fmt.Println(counter)
		}
	}
}

How other way can I write it with two for loops?

答案1

得分: 5

这是另一种方法来完成它,而不是每次都将字符串连接起来...

func manyG2() {
    for i := 0; i < 25; i++ {
        for j := 0; j <= i; j++ { // G的数量等于行号
            fmt.Print("G")
        }
        fmt.Println()
    }
}
英文:

Here is the another way to do it, instead of concatenating every time to the string ...

func manyG2() {
    for i := 0; i &lt; 25; i++ {
	    for j := 0; j &lt;= i; j++ { // num of Gs are equal to the row no.
		    fmt.Print(&quot;G&quot;)
	    }
	    fmt.Println()
    }
}

huangapple
  • 本文由 发表于 2017年4月29日 02:45:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/43686994.html
匿名

发表评论

匿名网友

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

确定