在C#中对二维数组执行任何任务时,出现错误“ CS0022:索引数1' inside [], expected
2'错误。”
static void Main(string[] args)
{
int sum = 0, max = 0;
int [,] ar = new int[6,6] {{ -1,-1, 0,-9,-2,-2},
{ -2,-1,-6,-8,-2,-5},
{ -1,-1,-1,-2,-3,-4},
{ -1,-9,-2,-4,-4,-5},
{ -7,-3,-3,-2,-9,-9},
{ -1,-3,-1,-2,-4,-5}};
for(int i = 0 ; i<4 ; i++)
{
for(int j = 0 ; j<4 ; j++)
{
sum =(
ar[ i ][ j ] +
ar[ i ][j+1] +
ar[ i ][j+2] +
ar[i+1][j+1] +
ar[i+2][ j ] +
ar[i+2][j+1] +
ar[i+2][j+2] );
if(sum > max )
{
max = sum;
}
else
{}
}
}
Console.WriteLine(max);
}
它应该打印出最大的沙漏总和,应该为-6,但是会出现错误。
答案 0 :(得分:1)
对数组建立索引时,请使用[n,m]而不是[n] [m]。 您还需要在主目录中添加“ public”。 这是正确的代码:
public static void Main(string[] args)
{
int sum = 0, max = 0;
int [,] ar = new int[6,6] {{ -1,-1, 0,-9,-2,-2},
{ -2,-1,-6,-8,-2,-5},
{ -1,-1,-1,-2,-3,-4},
{ -1,-9,-2,-4,-4,-5},
{ -7,-3,-3,-2,-9,-9},
{ -1,-3,-1,-2,-4,-5}};
for(int i = 0 ; i<4 ; i++)
{
for(int j = 0 ; j<4 ; j++)
{
sum =(
ar[ i , j ] +
ar[ i ,j+1] +
ar[ i ,j+2] +
ar[i+1,j+1] +
ar[i+2, j ] +
ar[i+2,j+1] +
ar[i+2,j+2] );
if(sum > max )
{
max = sum;
}
else
{}
}
}
Console.WriteLine(max);
}