为什么这段 Golang 代码返回的是 2 而不是 5 次?

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

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.

huangapple
  • 本文由 发表于 2023年2月9日 00:48:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389060.html
匿名

发表评论

匿名网友

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

确定