c#尝试打印数组时出现indexoutofrangeaccepeption错误
本文关键字:indexoutofrangeaccepeption 错误 数组 打印 | 更新日期: 2023-09-27 18:08:46
新来的c#程序员,
我正在编写一个简单的程序来打印出一个数字的前10个乘法表。这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Times_tables_calculator
{
class Program
{
static void Main(string[] args)
{
int number;
int counter;
int timestable;
int[] TimeTableList = new int[10];
counter = 0;
Console.WriteLine("Enter a number:");
number = int.Parse(Console.ReadLine());
while (counter <= 10)
{
timestable = (number * counter);
TimeTableList[counter] = timestable;
counter = (counter + 1);
}
Console.WriteLine("The times tables for " + number + " are:");
TimeTableList.ToList().ForEach(i => Console.WriteLine(i.ToString()));
Console.Read();
}
}
}
然而,当我在visual studio中运行程序时,我得到一个IndexOutOfRangeAcception错误:
TimeTableList[counter] = timestable;
任何帮助将感激我应该如何解决这个问题。
谢谢!
变化
while (counter <= 10)
while (counter < 10)
你的循环从0开始到10结束索引,也就是11个元素
要么改变
while (counter <= 9)
或
while (counter < 10)
你正在尝试访问数组索引11。数组索引从0开始。所以你需要从条件中减去1或者在条件
=
计数器必须小于10,不能小于等于。数组从0开始计数。然后你的元素索引从0到9