导致死机的原因:运行时错误:索引超出范围 [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)

}


守着星空守着你
浏览 155回答 2
2回答

繁花不似锦

您应该更改为 。arrLen := len(nums) + 1arrLen := len(nums)数组长度为 4。为此,索引为 0,1,2,3。但是当你试图做.该值现在是 。但你只有4个元素。并从循环中尝试获取数组中不存在的元素。这将为您提供运行时错误,并且会崩溃。arrLen := len(nums) + 1arrlen5这个将为你工作: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检查您是否仅访问数组中存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)}在的那些元素,而不是超出该元素。在 Go 规格中阅读此内容
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go