英文:
Why does this golang code return 2 times instead of 5?
问题
我不知道。
英文:
I don't have any idea.
package main
import "fmt"
func main() {
mySlc := []int{1, 2}
count := 0
num := 5
fmt.Println(len(mySlc))
fmt.Print("Enter Len:")
for i := 0; i <= num-len(mySlc); i++ {
count++
var eded int
fmt.Print("Enter i:")
fmt.Scan(&eded)
mySlc = append(mySlc, eded)
}
fmt.Println(mySlc, count)
}
I don't have any idea.
Why does this golang code return 2 times instead of 5?
答案1
得分: 2
mySlc
在每次循环迭代中都在发生变化,并且请注意i <= num - len(mySlc)
在每次循环运行时都会被评估。您可以通过将其转换为while循环并在每次迭代中检查num - len(mySlc)
的状态来进行交互式查看。
英文:
mySlc
is being mutated during each loop iteration, and note that the i <= num - len(mySlc)
is being evaluated on each loop run. You can view this interactively by converting this to a while-loop with
for {
...
}
and inspecting the state of num - len(mySlc)
at each iteration.
答案2
得分: 2
好的,以下是翻译好的内容:
好的,没错。
- 循环的第一次迭代。i=0,0 <= 5-2,好的。添加一个元素。
- 第二次迭代。i=1,1 <= 5-3,好的。添加一个元素。
- 第三次迭代。i=2,2 <= 5-4,不好。循环结束。
英文:
Well, that's right.
- The first iteration of the loop. i=0, 0 <= 5-2, Ok. An element is added.
- The second iteration. i=1, 1 <= 5-3, Ok. An element is added.
- The third iteration. i=2, 2 <= 5-4, No Ok. The cycle ends.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论