这里有新的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;
如果我应该解决这个问题,我们将不胜感激。
谢谢!
答案 0 :(得分:1)
更改
while (counter <= 10)
到
while (counter < 10)
你的循环从0开始并以10索引结束,这是11个元素
答案 1 :(得分:0)
要么改变
while (counter <= 9)
OR
while (counter < 10)
您正在尝试访问数组索引11.数组索引从0开始。因此您需要从条件中减1或在条件中删除=
答案 2 :(得分:0)
计数器必须低于10而不低于等于。数组从0开始计数。然后,您的元素将从0到9进行索引。