Multiple variables in multiple for loops in Go

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

Multiple variables in multiple for loops in Go

问题

我有两个带有两组不同变量的for循环,其中我还在下一个循环中重用了一个变量。代码大致如下:

func naive(z, x, y []uint32, n int) {
    var i, j, k int
    var A, B uint32

    for i = 0; i < n; i++ {
        B = 0

        for j = 1; j <= i; j++ {
            muladd(x[j], y[i - j], &A)
        }

        for k = 1; j < n; j++, k++ {
            muladd(x[j], y[n - k], &B)
        }
    }
}

但是我在第二个for循环处遇到了一个错误消息。它说missing { after for clause。有什么办法可以解决吗?

英文:

I have two for loops with two different set of variables, where I also reuse one variable from one loop in the next. The code looks roughly like this:

func naive(z, x, y []uint32, n int) {
	var i, j, k int
	var A, B uint32

	for i = 0; i &lt; n; i++ {
		B = 0

		for j = 1; j &lt;= i; j++ {
			muladd(x[j], y[i - j], &amp;A)
		}

		for k = 1; j &lt; n; j++, k++ {
			muladd(x[j], y[n - k], &amp;B)
		}
	}
}

But I get an error message at the second for loop. It says missing { after for clause. Any ideas how to solve it?

答案1

得分: 1

当你在最后一个循环中同时增加j和k时,Go语言不喜欢这样做。

所以尝试将你的代码改为:

func naive(z, x, y []uint32, n int) {
    var i, j, k int
    var A, B uint32

    for i = 0; i < n; i++ {
        B = 0

        for j = 1; j <= i; j++ {
            muladd(x[j], y[i-j], &A)
        }

        for k = 1; j < n; j++ {
            muladd(x[j], y[n-k], &B)
            k++
        }
    }
}

注意最后一个循环,我只是将k++语句移到了循环内部。

英文:

when you increment both j and k on the last loop go doesn't like it

so try to change your code to

func naive(z, x, y []uint32, n int) {
	var i, j, k int
	var A, B uint32

	for i = 0; i &lt; n; i++ {
		B = 0

		for j = 1; j &lt;= i; j++ {
			muladd(x[j], y[i-j], &amp;A)
		}

		for k = 1; j &lt; n; j++ {
			muladd(x[j], y[n-k], &amp;B)
            k++
		}
	}
}

pay attention to the last loop I just moved the k++ statement inside the loop

huangapple
  • 本文由 发表于 2017年6月11日 07:09:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/44478920.html
匿名

发表评论

匿名网友

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

确定