首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我得到的索引超出了数组错误的范围

我得到的索引超出了数组错误的范围
EN

Stack Overflow用户
提问于 2017-10-22 16:14:25
回答 2查看 44关注 0票数 1

所以,我已经做了一个程序,它应该收集你输入的数字的数量,然后倒数。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace K4_Labb_3
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.Write("Ange antalet heltal du vill lagra i fältet: ");

            int heltal = int.Parse(Console.ReadLine());

            int[] i = new int[heltal];

            Console.WriteLine("Ange " + heltal + " heltal: ");

            for (int j = 0; j < i.Length; j++)
            {
                int o = int.Parse(Console.ReadLine());
                i[j] = o;

            }

            Console.WriteLine("Talen utskrivna baklänges: " );
            for (int l = i.Length; l > 0; l--)
            {

                Console.Write(i[l]);
            }


        }
    }
}

但我得到的错误是"index I out of the array“,我想知道是否有人可以帮助我,并解释出问题所在。

EN

回答 2

Stack Overflow用户

发布于 2017-10-22 16:16:53

这里的问题:

代码语言:javascript
复制
        for (int l = i.Length; l > 0; l--)

当你有一个长度为LEN的数组时,那么你只能访问索引为0, 1, 2, ..., LEN-1的元素。

票数 3
EN

Stack Overflow用户

发布于 2017-10-22 16:22:06

在打印数组时,您从超过限制的一个位置开始。如果长度是5,那么数组的位置将是0,1,2,3,4。但是在你的程序中,当你打印的时候,你是从5开始的,它抛出了错误,这是正确的。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.Write("Ange antalet heltal du vill lagra i fältet: ");

            int heltal = int.Parse(Console.ReadLine());

            int[] i = new int[heltal];

            Console.WriteLine("Ange " + heltal + " heltal: ");

            for (int j = 0; j < i.Length; j++)
            {
                int o = int.Parse(Console.ReadLine());
                i[j] = o;

            }

            Console.WriteLine("Talen utskrivna baklänges: ");
            for (int l = i.Length-1; l >= 0; l--)
            {

                Console.Write(i[l]);
            }


        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46871918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档