在for循环中,最后一次迭代被跳过并且不会被打印出来。

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

last iteration gets skipped and not printed in a for loop

问题

我正在尝试构建一段代码,当用户输入一系列数字时,它将遍历该序列,比较每个数字,并对于序列中的每个新的最大数字,它将对之前的所有数字求和。

func main() {
    var numeri []int
    numeri = GetInputSlice()
    fmt.Println(numeri)
    var sum int
    num := len(numeri)
    for i := 0; i < num-1; i++ {
        sum += numeri[i]
        if numeri[i] > numeri[i+1] || i == num-2 {
            fmt.Println(sum)
            sum = 0
        }
    }
}

完整的代码在这里:https://go.dev/play/p/13ljQPmKaRA

如果我输入这个数字序列 [1 2 13 0 7 8 9 -1 0 2],我希望得到 16、24 和 1。但是在我的代码中,我只得到了 16 和 24,而没有得到最后的 1,我无法找到解决这个问题的方法。

英文:

Im trying to build a code that when the user inputs a sequence of numbers it will go through the sequence comparing each numbers and for every new biggest number in the sequence it will sum all the previous ones

func main() {
    var numeri []int
    numeri = GetInputSlice()
    fmt.Println(numeri)
    var sum int
    num := len(numeri)
    for i := 0; i &lt; num - 1 ; i++ {
        sum += numeri[i]
        if numeri[i] &gt; numeri[i+1] || numeri[i] == num - 1 {
            fmt.Println(sum)
            sum = 0
        }
    }
}

full code over here: https://go.dev/play/p/13ljQPmKaRA

if I input this sequence of numbers [1 2 13 0 7 8 9 -1 0 2] I would like to get 16, 24 and 1.
But in my code I only get 16 and 24 without getting the last 1 and I can't figure out a way to fix this.

答案1

得分: 0

只有numeri[i]被添加到sum中,而且你的循环从未访问最后一个元素(i < num - 1),那么最后一个元素怎么可能被添加呢?

遍历整个切片,执行加法,但只有在不是最后一个元素时才与下一个元素进行比较。如果我们在最后一个元素上,我们也想要打印,所以我们可以使用一个条件:

i == max || numeri[i] > numeri[i+1]

其中,如果i == max,则不会执行与下一个元素的比较(短路评估)。

例如:

max := len(numeri) - 1
for i, v := range numeri {
	sum += v
	if i == max || v > numeri[i+1] {
		fmt.Println(sum)
		sum = 0
	}
}

这将输出(在Go Playground上尝试):

[1 2 13 0 7 8 9 -1 0 2]
16
24
1
英文:

Only numeri[i] is ever added to sum, and your loop never visits the last item (i &lt; num - 1), so how could the last item be ever added?

Range through the whole slice, perform the addition, but only compare to the next element if you're not at the last one. If we're at the last one, we also want to print, so we may use a single condition

i == max || numeri[i] &gt; numeri[i+1]

Where the comparison to the next element will not be executed if i == max (short circuit evaluation).

For example:

max := len(numeri) - 1
for i, v := range numeri {
	sum += v
	if i == max || v &gt; numeri[i+1] {
		fmt.Println(sum)
		sum = 0
	}
}

This will output (try it on the Go Playground):

[1 2 13 0 7 8 9 -1 0 2]
16
24
1

huangapple
  • 本文由 发表于 2022年6月8日 16:55:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/72542806.html
匿名

发表评论

匿名网友

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

确定