所以,我已经做了一个程序,它应该收集你输入的数字的数量,然后倒数。
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“,我想知道是否有人可以帮助我,并解释出问题所在。
发布于 2017-10-22 16:16:53
这里的问题:
for (int l = i.Length; l > 0; l--)当你有一个长度为LEN的数组时,那么你只能访问索引为0, 1, 2, ..., LEN-1的元素。
发布于 2017-10-22 16:22:06
在打印数组时,您从超过限制的一个位置开始。如果长度是5,那么数组的位置将是0,1,2,3,4。但是在你的程序中,当你打印的时候,你是从5开始的,它抛出了错误,这是正确的。
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]);
}
}
}
}https://stackoverflow.com/questions/46871918
复制相似问题