猿问

导致恐慌的原因:运行时错误:索引超出范围 [4],长度为 4,即使数组已初始化为动态数组

我已经初始化了一个动态数组,但它显示索引超出范围。我也尝试过给出固定长度,但它也显示了同样的错误。错误描述:恐慌:运行时错误:索引超出范围 [4],长度为 4


package main

import "fmt"

func missingNumber(nums []int) int {

arrSum := 0

arrLen := len(nums) + 1

for i := 0; i < arrLen; i++ {

arrSum += nums[i]

}

numSum := arrLen * (arrLen + 1) / 2

missingNumber := numSum - arrSum

return missingNumber

}

func main() {

nums := []int{1, 3, 4, 5}

result := missingNumber(nums)

fmt.Println(result)

}


小唯快跑啊
浏览 132回答 2
2回答

拉丁的传说

您应该更改arrLen := len(nums) + 1为arrLen := len(nums).您的数组长度为 4。为此,索引为 0,1,2,3。但是当你试图做 arrLen := len(nums) + 1. 现在的arrlen值是5。但你只有 4 个元素。并从您的循环中尝试获取数组中不存在的元素。这会给你一个运行时错误,它会恐慌。这个对你有用:package mainimport "fmt"func missingNumber(nums []int) int {arrSum := 0arrLen := len(nums)for i := 0; i < arrLen; i++ {arrSum += nums[i]}m := arrLen + 1numSum := m * (m + 1) / 2missingNumber := numSum - arrSumreturn missingNumber}func main() {nums := []int{1, 3, 4, 5}result := missingNumber(nums)fmt.Println(result)}

叮当猫咪

这是您的程序中的更正,用于从自然数序列中查找单个缺失的数字。您正在索引数组 nums[len(nums) + 1] 超出数组的范围。如果允许,这应该访问随机内存并读取任何合法的垃圾值,您甚至不会知道如此难以发现的错误。好消息是 Go 正在检查您是否只访问数组中的那些元素,而不是超出这些元素。在 Go 规范中阅读此内容package mainimport "fmt"func missingNumber(nums []int) int {&nbsp; &nbsp; arrSum := 0&nbsp; &nbsp; arrLen := len(nums)&nbsp; &nbsp; for i := 0; i < arrLen; i++ {&nbsp; &nbsp; &nbsp; &nbsp; arrSum += nums[i]&nbsp; &nbsp; }&nbsp; &nbsp; //let n be the total natural number: which will be provided plus 1 missing&nbsp; &nbsp; n := arrLen + 1&nbsp; &nbsp; numSum := n * (n + 1) / 2&nbsp; &nbsp; missingNumber := numSum - arrSum&nbsp; &nbsp; return missingNumber}func main() {&nbsp; &nbsp; nums := []int{1, 3, 4, 5}&nbsp; &nbsp; result := missingNumber(nums)&nbsp; &nbsp; fmt.Println(result)}或者,您可以使用范围循环来确保安全or _, i := range nums { ...:package mainimport "fmt"func missingNumber(nums []int) int {&nbsp; &nbsp; arrSum := 0&nbsp; &nbsp; arrLen := len(nums)&nbsp; &nbsp; for _, i := range nums {&nbsp; &nbsp; &nbsp; &nbsp; arrSum += i&nbsp; &nbsp; }&nbsp; &nbsp; //let n be the total natural number; which will be provided plus 1 missing&nbsp; &nbsp; n := arrLen + 1&nbsp; &nbsp; numSum := n * (n + 1) / 2&nbsp; &nbsp; missingNumber := numSum - arrSum&nbsp; &nbsp; return missingNumber}func main() {&nbsp; &nbsp; nums := []int{1, 3, 4, 5}&nbsp; &nbsp; result := missingNumber(nums)&nbsp; &nbsp; fmt.Println(result)}
随时随地看视频慕课网APP

相关分类

Go
我要回答