英文:
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 < 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)
}
}
}
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 < 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++
}
}
}
pay attention to the last loop I just moved the k++
statement inside the loop
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论