英文:
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 <= 24; i++ {
for x := 0; x == 0; x++ {
counter += "G"
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 < 25; i++ {
for j := 0; j <= i; j++ { // num of Gs are equal to the row no.
fmt.Print("G")
}
fmt.Println()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论