我正在编写一个程序,它从键盘输入并以下面的螺旋方式打印方形矩阵
1 2 3
8 9 4
7 6 5
Run Code Online (Sandbox Code Playgroud)
我设法编写程序,但我遇到了一个奇怪的错误.在第26行,它给了我一个超出范围的索引异常
while (matrix[row, col] == 0 && col < matrix.GetLength(0) )
Run Code Online (Sandbox Code Playgroud)
但是,如果我在循环中切换两个语句的顺序,异常就消失了?这是否意味着while循环中两个语句的顺序很重要?如果是,为什么?如果两个语句都是真的执行循环,并且如果其中一个是假的,无论是哪一个,都应该停止执行它.
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpiralMatrixN
{
class Program
{
static void Main(string[] args)
{
//prompt the user to enter n
Console.WriteLine("Enter the value of n");
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n,n];
Console.Clear();
System.Console.SetWindowSize(100, 30);
int value = 1;
int col = 0;
int row = 0;
if (n>0 && n<21)
{
while(value <= n*n)
{
while (matrix[row, col] == 0 && col < matrix.GetLength(0) )
{
matrix[row, col++] = value;
value++;
}
col--;
row++;
while (row < matrix.GetLength(1) && matrix[row, col] == 0)
{
matrix[row++, col] = value;
value++;
}
row--;
col--;
while (col >= 0 && matrix[row, col] == 0 )
{
matrix[row, col--] = value;
value++;
}
col++;
row--;
while (matrix[row, col] == 0 && row >= 0)
{
matrix[row--, col] = value;
value++;
}
col++;
row++;
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.SetCursorPosition(j * 5, i * 2);
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*rei 15
是的,订单很重要.&&子句中的条件按优先顺序执行,如果一个失败,则不执行另一个条件.目前您所遇到的是因为matrix[row, col] == 0首先执行,并且col超出范围.所以你的检查col(这是绝对正确的btw)应该是第一个:
while (col < matrix.GetLength(0) && matrix[row, col] == 0)
Run Code Online (Sandbox Code Playgroud)
如果失败,则不会执行第二个语句,并且您不会出错.这称为"短路评估".