Hallo, Ich bin ein Anfänger in C# und es verstand nicht, warum die Ausnahme auf dem Programm geworfen wird unten gezeigtSystem.IndexOutOfRangeException Fehler nicht verstanden
PROGRAMM:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int n, i, x=0, y=0;
Console.WriteLine("Enter the degree of matrix:");
n = int.Parse(Console.ReadLine());
int[,] num = new int[n, n];
int p = n * n;
for (i = 1; i <= p; i++)
{
num[x, y] = i;
if (num[x, y] % n == 0) { y++; }
if (y % 2 == 0) { x++; }
if (y % 2 != 0) { x--; }
}
for (i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Console.Write(num[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
gewünschtes Ergebnis:
Enter order of matrix:
4
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13
Aber eine Ausnahme wie im Thema angegeben wird auf num [x, y] = i geworfen; . Ich verstehe nicht, warum System.IndexOutOfRangeException auftritt, da die Schleife eindeutig am Ende des 2d-Arrays endet.
P.S. Das Programm soll nur einmal ausgeführt werden.