英文:
Golang for loop continues counting
问题
我正在尝试使一个for循环在字符串包含特定数字时停止。唯一的问题是,在将31添加到计数器后,它停止向字符串添加值。我觉得它在赶得太快,无法追赶上。我知道总有其他方法来完成任务,但我只想知道为什么会这样。
我想要实现的是让计数器充当高度。theSlice = 8,webSlices是一个列表。整个文本说"Height is a 1",所以我想知道高度是什么数字,并使计数器等于该数字。
代码:
func breakDownSlice(theSlice int, webSlices []string) {
counter := 0
done := false
for done == false {
log.Println(webSlices[theSlice])
log.Println(counter)
done = strings.Contains(webSlices[theSlice], string(counter))
if done == true {
log.Printf("The height is %d", counter)
} else {
counter++
}
}
}
英文:
I am trying to make a for loop stop when a string contains a certain numeral. The only problem is it stops adding value to the string after adding 31 to the counter. I feel it is going to fast before it can play catch up. I know there's always another way to complete the task but I would just want to understand why it does this.
What I'm trying to accomplish is having the counter act as the height. The theSlice = 8 and webSlices is a list. The whole text says "Height is a 1" so I am trying to see what number is the height and make counter equal that.
Code:
func breakDownSlice(theSlice int, webSlices []string) {
counter := 0
done := false
for done == false {
log.Println(webSlices[theSlice])
log.Println(counter)
done = strings.Contains(webSlices[theSlice], string(counter))
if done == true {
log.Printf("The height is %d", counter)
} else {
counter++
}
}
}
答案1
得分: 1
string(counter)
在这里无法工作,应该使用strconv.Itoa(counter)
代替。
英文:
the line
done = strings.Contains(webSlices[theSlice], string(counter))
string(counter)
can't work here, use strconv.Itoa(counter)
instead
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论