【问题标题】:compile error:index out of range编译错误:索引超出范围
【发布时间】:2010-12-18 07:43:41
【问题描述】:

我想写合并排序算法,当我调试程序并给它数字时,它会出现索引超出范围错误,我的代码有什么问题?提前谢谢。

    private void button3_Click(object sender, EventArgs e)
    {


        string[] source = textBox1.Text.Split(',');
        string[] source1 = textBox3.Text.Split(',');
        int[] nums2 = new int[source1.Length + source.Length];
        int[] nums = new int[source.Length];
        for (int i = 0; i < source.Length; i++)
        {
            nums[i] = Convert.ToInt32(source[i]);

        }
        int[] nums1 = new int[source1.Length];
        for (int j = 0; j < source1.Length; j++)
        {
            nums1[j] = Convert.ToInt32(source1[j]);
        }
        int x=0;
        int y=0;
           int z=0;

        while (x <=nums.Length && y <= nums1.Length)
        {
            if (nums[x] <= nums1[y])///it gives out of range on this line
            {
                nums2[z] = nums[x];
                x++;

            }
            else
            {
                nums2[z] = nums1[y];
                y++;
            }

            z++;
        }
        if (x > nums.Length)
        {
            while (y <= nums1.Length)
            {
                nums2[z] = nums1[y];

                z++;
                y++;
            }
            if (y > nums1.Length)
            {
                while (x <= nums.Length)
                {
                    nums2[z] = nums[x];
                    z++;
                    x++;
                }
            }
        }
        string merge = nums2[z].ToString();

       textBox4.Text = merge;

    }
}

【问题讨论】:

    标签: c# winforms algorithm mergesort


    【解决方案1】:

    首先,IndexOutOfRangeException 不是编译错误,而是运行时错误。

    数组中的索引是从 0 开始的。这意味着例如长度为 3 的数组具有索引 0、1 和 2,但索引 3 不存在并且超出范围。要修复您的错误,请将以下几行的 &lt;= 更改为 &lt;

    while (x < nums.Length && y < nums1.Length)
    
    while (y < nums1.Length)
    
    while (x < nums.Length)
    

    等等……

    您的程序中也可能存在其他错误 - 这只是我看到的第一个错误。

    【讨论】:

    • 已解决,谢谢,但正如你所说,它也有其他问题,因为它给出了输出 0
    【解决方案2】:

    数组在 C# 中从零开始,这意味着数组中的第一项位于索引 0,而不是索引 1。

    但是,Length 属性返回从 1 开始的数组中对象数的计数。因此,当您编写 x &lt;= nums.Length 时,实际上是在尝试访问超出数组边界的索引。

    相反,您应该将代码的该部分重写为:

        while (x < nums.Length && y <  nums1.Length)
        {
            if (nums[x] <= nums1[y])
            {
                nums2[z] = nums[x];
                x++;
    
            }
    
        // etc.
    

    【讨论】:

      【解决方案3】:

      索引从0 开始,所以你应该这样做:

      while (x < nums.Length && y < nums1.Length)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        • 2016-04-17
        • 2015-07-13
        相关资源
        最近更新 更多