using System;
class MagicSquare
{
int[,] magic;
public MagicSquare(int n)
{
magic = new int[n, n]; int i;
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
magic[i, j] = 0;
//
i = 0;
j = (n - 1) / 2; //calculate the middle of the fisrt row
magic[i, j] = 1;
int next = 2; while (next <= n * n)
{
int row = (i - 1) % n;
int col = (j + 1) % n; if (row < 0)
row = n - 1; if (magic[row, col] != 0)
i = (i + 1) % n;
else
{
i = row;
j = col;
} magic[i, j] = next;
next++;
}
}
public void ShowMagicSquare()
{
for (int i = 0; i < magic.GetLength(1); i++)
{
for (int j = 0; j < magic.GetLength(1); j++)
Console.WriteLine("{0:00}", magic[i, j]); Console.WriteLine();
}
}
}public class IDNumberAp
{
public static void Main(string[] args)
{
int n = Convert.ToInt32(args[0]);
MagicSquare x = new MagicSquare(n);
x.ShowMagicSquare();
}
} 调试错误:索引超出数组范围
class MagicSquare
{
int[,] magic;
public MagicSquare(int n)
{
magic = new int[n, n]; int i;
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
magic[i, j] = 0;
//
i = 0;
j = (n - 1) / 2; //calculate the middle of the fisrt row
magic[i, j] = 1;
int next = 2; while (next <= n * n)
{
int row = (i - 1) % n;
int col = (j + 1) % n; if (row < 0)
row = n - 1; if (magic[row, col] != 0)
i = (i + 1) % n;
else
{
i = row;
j = col;
} magic[i, j] = next;
next++;
}
}
public void ShowMagicSquare()
{
for (int i = 0; i < magic.GetLength(1); i++)
{
for (int j = 0; j < magic.GetLength(1); j++)
Console.WriteLine("{0:00}", magic[i, j]); Console.WriteLine();
}
}
}public class IDNumberAp
{
public static void Main(string[] args)
{
int n = Convert.ToInt32(args[0]);
MagicSquare x = new MagicSquare(n);
x.ShowMagicSquare();
}
} 调试错误:索引超出数组范围
public static void Main(string[] args)
{
int n = Convert.ToInt32(args[0]);
正解!
{
int n = Convert.ToInt32(args[0]);
MagicSquare x = new MagicSquare(n);
x.ShowMagicSquare();
}
很明显args里没有东西
要赋值
string [] xx={"....","....."}自己写
调用Main(xx);
public static void Main(string[] args)
{
int n=int.ParseConsole.ReadLine();
MagicSquare x = new MagicSquare(n);
x.ShowMagicSquare();
}