using System;//異常類
// ArithmeticException [erismetik]算術 NotFiniteNumberException[finity]有限的
class class1
...{
int[,] mm;
static void Main()
...{
do
...{
class1 myclass1 = new class1();
try
...{
int n; Console.Write("魔術矩陣輸入矩陣大小退出程序請輸入零: ");
n = int.Parse(Console.ReadLine());
if (n == 0)
...{
break;
}
if (n % 2 == 0)
...{
Console.Write("要輸入的數字必須是奇數! 請重新");
continue;
}
myclass1.mm = new int[n, n];
myclass1.AssignValue(n);
myclass1.PrintOut(n);
Console.WriteLine(" ");
Exception x=new Exception("計算完成!");
throw x;
}
catch (Exception e)
...{
Console.Write("{0} 請再次","注意:"+e.Message );
}
}
while (true);
}
void AssignValue(int n)//賦值[asing]
...{
int assignValue = 1;
int p = n - 1;
int column = p / 2;
int row = 0;
for (int i = 0; i<n;i++ )
...{//設置初始值為零
for (int j = 0; j < n; j++)
...{
mm[i,j]=0;
}
}
mm[row, column] = assignValue;//填充第一個
do
...{//循環1~n的平方數字填充
assignValue++;//填充下一個
column--;row--;//常規算法的下一個位置//下面是三個特殊情況
if (column < 0 & row < 0)
...{//如果是左上角則放在其下
row += 2; column += 1;
}
else
...{//如果行列小於零就移動到最大處
if (column < 0) column = p;
if (row < 0) row = p;
}
if (mm[row, column] != 0)
...{//如果遇到已經填充的位置就放在其下
column += 1; row += 2;
}
mm[row, column] = assignValue;
} while (assignValue < n * n);
}
void PrintOut(int n)
...{
for (int i=0;i<n ;i++ )
...{
Console.WriteLine();
for (int j = 0; j < n; j++)
...{
//Console.Write(mm[i, j] + " ");
int m=n/10+1;
string strS=new string(''0'',m);
Console.Write("{0:" + strS + "# }", mm[i, j]);
}
}
}
}