在我的阵列上,在第40行,我的边界在数组之外,但我不知道如何格式化,因为这是我的第一个带有多维数组的程序。请帮我。谢谢! (第40行是array[i, 0] = randomArray.Next(0, 100);
)
namespace Exercise6
{
class Program
{
static void Main(string[] args)
{
OtherClass aTable = new OtherClass(); //instantiate class
Console.WriteLine("How many rows do you want your two-dimensional array to be?");
aTable.SRows = Console.ReadLine(); //reads input for how many rows that the user would like
aTable.IntRows = int.Parse(aTable.SRows); //convert rows to int
Console.WriteLine("Thanks you! How many columns would you like your two-dimensional arry to be?");
aTable.SColumns = Console.ReadLine(); //reads input for how many columns that the user would like
aTable.IntColumns = int.Parse(aTable.SColumns); //convert columns to int
//set two dimensional array based upon the size that the user has requested
int[ , ] array = new int[aTable.IntColumns, aTable.IntRows];
Random randomArray = new Random(); //call to random class to ask for random numbers
for (int i = 0; i <= aTable.IntColumns; i++) // rows
{
array[i, 0] = randomArray.Next(0, 100); // for every value in each row, insert a random number
}
//both arrays here are overloaded. See this site to see if can get help. Site is below after last close loop
for (int y = 0; y <= aTable.IntRows; y++) // columns
{
array[y, y] = randomArray.Next(0, 100);
}
Console.WriteLine(array);
}
}
}
namespace Exercise6
{
class OtherClass
{
private string sRows;
public string SRows { get; set; }
private int intRows;
public int IntRows { get; set; }
private string sColumns;
public string SColumns { get; set; }
private int intColumns;
public int IntColumns { get; set; }
}
}
答案 0 :(得分:2)
将循环条件更改为i < aTable.IntColumns
循环从0开始并转到aTable.IntColumns - 1
并且代码变为
for (int i = 0; i < aTable.IntColumns; i++)
{
array[i, 0] = randomArray.Next(0, 100);
}
答案 1 :(得分:2)
由于数组基于零,因此无法达到最大值:
// This line is incorrect
for (int i = 0; i <= aTable.IntColumns; i++)
那一行应该是:
for (int i = 0; i < aTable.IntColumns; i++)
这将让它从0
转到aTable.IntColumns-1
,它们是aTable.IntColumns
长度数组的有效索引。行也是如此。
答案 2 :(得分:1)
C#数组使用零相对偏移量作为其索引。这意味着对于长度为 n 的数组,其索引 i 的域为0 <= i <= n-1
。 100个元素的数组的索引范围为0-99。如果您尝试使用随机值填充m * n数组。
如果您的作业是填充具有随机值的数组(似乎很可能),您需要执行以下操作:
for ( int i=0 ; i < aTable.IntRows ; i++ ) // rows
{
for ( int j= 0 ; i < aTable.IntColumns ; j++ )
{
array[i,j] = randomArray.Next(0,100); // for every value in each row, insert a random number
}
}
您可能还注意到您的注释与您的代码不匹配:您正在迭代行并检查列限制,反之亦然。
答案 3 :(得分:0)
错误在for循环中:
for (int i = 0; i < aTable.IntColumns; i++) // rows
{
array[i, 0] = randomArray.Next(0, 100); // for every value in each row, insert a random number
}
i < aTable.IntColumns
应该是停止标准