String 恐慌:尝试访问字符串元素时索引超出Go的范围
我目前正在学习如何在Go中编码,我遇到了代码第43行和第44行出现的问题,我正在尝试将“num”和“den”的一个元素转换为一个数字,以便以后可以使用它进行我想要的计算,但我得到了以下消息:String 恐慌:尝试访问字符串元素时索引超出Go的范围,string,go,indexing,panic,String,Go,Indexing,Panic,我目前正在学习如何在Go中编码,我遇到了代码第43行和第44行出现的问题,我正在尝试将“num”和“den”的一个元素转换为一个数字,以便以后可以使用它进行我想要的计算,但我得到了以下消息: panic: runtime error: index out of range goroutine 1 [running]: main.iterate_transfer(0x7ffecd96f050, 0x3, 0x7ffecd96f054, 0x3) /home/mlg/Program
panic: runtime error: index out of range
goroutine 1 [running]:
main.iterate_transfer(0x7ffecd96f050, 0x3, 0x7ffecd96f054, 0x3)
/home/mlg/Programming/project/107transfer_2019/107transfer.go:43 +0x3af
main.main()
/home/mlg/Programming/project/107transfer_2019/107transfer.go:28 +0xac
我试图打印len和“den”字符串的内容,它在正确的位置包含我想要的值,所以我不理解为什么我不能访问它的单个元素
我把“7*2*6”传给了num_str,把“2*4*3”传给了den_str
我的代码:
34 func iterate_transfer(num_str, den_str string) () {
35 result := 0.0
36
37 for x := 0.0; x <= 1.00; x += 0.001 {
38 num := strings.Split(num_str, "*")
39 den := strings.Split(den_str, "*")
40 power_num := len(num)
41 power_den := len(den)
42 for s := len(num); s > 0; s-- {
43 num_nb, _ := strconv.Atoi(num[s])
44 den_nb, _ := strconv.Atoi(den[s])
45 result += math.Pow(float64(num_nb), float64(power_den)) / math.Pow(float64(den_nb), float64(power_den))
46 power_num--
47 power_den--
48 }
49 fmt.Println(x, " -> ", result, "\n")
50 }
51 }
34函数迭代传输(num\u str,den\u str string)(){
35结果:=0.0
36
37对于x:=0.0;x 0;s--{
43 num_nb,:=strconv.Atoi(num[s])
44登岛,登岛:=strconv.Atoi(登岛)
45结果+=math.Pow(float64(num_nb),float64(power_den))/math.Pow(float64(den_nb),float64(power_den))
46次幂次--
47电源--
48 }
49 fmt.Println(x,“->”,结果“\n”)
50 }
51 }
提前谢谢你对我的帮助 在
len
内置方法中,返回给定元素的大小。
由于索引从0开始,您需要:
len
是否大于0李>
-1
,以访问索引你的射程偏离了1。为s:=len(num)-1尝试:
;s>=0;s--