doubei2340 2018-01-06 14:25
浏览 36
已采纳

我在运行以下代码时出现索引超出范围错误

i having the following code to print the indexes of an array which contains similar values.

but on running this code getting panic: indexes out of range run time error

why i am getting this

package main

import "fmt"

func main()  {
    var numbers[] int = [] int {5,2,3,5,3}
    var copy_numbers[] int
    var count [5] int
    var i,j int
    copy(copy_numbers,numbers)
    for i=0;i<len(numbers);i++ {
        for j=0;j<len(numbers) ;j++  {
            if numbers[i]==numbers[j] {
                count[i]++;
            }
        }
    }
    fmt.Printf("%d",count)

    for i=0;i<len(numbers) ;i++  {
        fmt.Println("hello")
        if count[i]>1{
            for j=0;j<len(numbers) ;j++  {
                if numbers[i]==copy_numbers[j] {

                    fmt.Printf("%d",j)

                }
            }
            fmt.Println("")
        }
    }

fmt.Printf("%d",count)

}
  • 写回答

4条回答 默认 最新

  • dongxianji0968 2018-01-06 14:37
    关注

    copy_numbers is of size 0, just as you initialized it.

    If I add the following before your first for loop:

    fmt.Println(numbers)
    fmt.Println(copy_numbers)
    

    I get:

    [5 2 3 5 3]
    []
    

    the copy builtin copies up to the length of either argument, as mentioned in the docs:

    Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

    You should initialize copy_numbers to be of the same length as numbers

      copy_numbers := make([]int, len(numbers))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格