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

我已经初始化了一个动态数组,但它显示索引超出范围。
我也尝试过给出固定长度,但它也显示了同样的错误。

错误描述:
panic: runtime error: index out of range [4] with length 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)
}
stack overflow What causes panic: runtime error: index out of range [4] with length 4 even though array is initialized as dynamic array
原文答案
author avatar

接受的答案

您应该将 arrLen := len(nums) + 1 更改为 arrLen := len(nums)

您的数组长度为 4。为此,索引为 0、1、2、3。但是当你尝试做 arrLen := len(nums) + 1 时。 arrlen 值现在是 5 。但你只有 4 个元素。从你的循环中你试图获得一个不存在于数组中的元素。这会给你一个运行时错误,它会恐慌。

这个对你有用:

package main

import "fmt"

func missingNumber(nums []int) int {
    arrSum := 0
    arrLen := len(nums)
    for i := 0; i < arrLen; i++ {
        arrSum += nums[i]
    }
    m := arrLen + 1
    numSum := m * (m + 1) / 2
    missingNumber := numSum - arrSum
    return missingNumber
}

func main() {
    nums := []int{1, 3, 4, 5}
    result := missingNumber(nums)
    fmt.Println(result)
}

答案:

作者头像

这是程序中的更正,用于从自然数序列中找到一个缺失的数字。你在索引数组 nums [len(nums) + 1] beyond the bounds of your array. If allowed this should access random memory and read any garbage value as legitimate and you would not even know about such hard to find bugs. The good thing is Go is checking that you access only those elements in array which are there and not beyond that. Read this in Go specs

package main

import "fmt"

func missingNumber(nums []int) int {
    arrSum := 0
    arrLen := len(nums)
    for i := 0; i < arrLen; i++ {
        arrSum += nums[i]
    }
    //let n be the total natural number: which will be provided plus 1 missing
    n := arrLen + 1
    numSum := n * (n + 1) / 2
    missingNumber := numSum - arrSum
    return missingNumber
}
func main() {
    nums := []int{1, 3, 4, 5}
    result := missingNumber(nums)
    fmt.Println(result)
}

或者,您可以使用范围循环来确保安全 or _, i := range nums { ...

package main

import "fmt"

func missingNumber(nums []int) int {
    arrSum := 0
    arrLen := len(nums)

    for _, i := range nums {
        arrSum += i
    }
    //let n be the total natural number; which will be provided plus 1 missing
    n := arrLen + 1
    numSum := n * (n + 1) / 2
    missingNumber := numSum - arrSum
    return missingNumber
}
func main() {
    nums := []int{1, 3, 4, 5}
    result := missingNumber(nums)
    fmt.Println(result)
}