登录
首页 >  Golang >  Go问答

For 循环以其主体结束

来源:stackoverflow

时间:2024-04-15 16:33:34 340浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《For 循环以其主体结束》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

for 循环以其主体结束,不再继续

我需要找到windex,检查它是否在切片中,如果没有添加值 我哪里出错了?

var x make(map[int]float32, 10)
var s []int
var value = 100
for i := 1; i <= 10; i++ {
    wIndex := int(rand.Intn(len(x))) // random Index choice among map values
    for _, v := range s {            //end of loop here (if exactly it returnts to loop before)
        if v != wIndex {
            s = append(s, wIndex)
            x[wIndex] += value
        }
    }
}

解决方案


您从一个空的 s 切片开始。因此,您永远不会进入向切片添加元素的内部 for 循环。

这是一种替代且直接的方法:

for i := 1; i <= 10; i++ {
    windex := int(rand.intn(len(x) + 1)) 
    found := false
    for _, v := range s {
        if v == windex {
            found = true
            break
        }
     }
     if !found {
        s = append(s, windex)
        x[windex] += float32(value)
     }
 }
  • 请注意,您需要将值转换为 float32,因此 x[windex] += float32(value) 而不仅仅是 x[windex] += value

  • rand.intn(n int) 会生成 [0,n) 范围内的数字,因此需要加 1 来覆盖适当的范围,避免地图为空时出现恐慌。

内部循环永远不会执行,因为切片没有值,它是空的,因此在切片中插入一个随机值,然后对其进行范围处理。

还有其他事情需要注意,因为 rand.intn 已经返回 int,所以不需要将其类型转换为 int。

int(rand.intn(len(x))) // no requirement to typecast it into int.

还有一件事是地图的长度是 0,这就是为什么 rand.intn 在运行代码时会抛出错误。

windex := int(rand.intn(len(x))) // this will throw an error.

如下更改您的代码。

package main

import (
    "fmt"
    "math/rand"
)

func main() {

    var x = make(map[int]float32)
    var s []int
    var value = 100
    for i := 1; i <= 10; i++ {
        wIndex := rand.Intn(10) // random Index choice among map values
        s = append(s, wIndex)
        for _, v := range s { //end of loop here (if exactly it returnts to loop before)
            if v != wIndex {
                x[wIndex] += float32(value)
            }
        }
    }
    fmt.Println(s)
    fmt.Println(x)
}

Go playground 上的工作示例

好了,本文到此结束,带大家了解了《For 循环以其主体结束》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>