using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication34
{
internal class Program
{
private static void Main(string[] args)
{
int row, colown, n, x, y;//行号,列号,阶数,下一行号,下一列号
colown = 0; y = colown - 1;
int[,] hf;//二维矩阵
while (true)//输入阶数
{
try
{
System.Console.WriteLine("请输入幻方阶数:");
n = Convert.ToInt32(System.Console.ReadLine());
break;
}
catch (Exception)
{
System.Console.WriteLine("请不要开玩笑,重新输入吧");
}
}
//初始化
row = n / 2; x = row - 1;
hf = new int[n, n];
hf[row, colown] = 1;
//幻方
for (int i = 2; i <= n * n; i++, x = row - 1, y = colown - 1)
{
x = x < 0 ? n - 1 : x;
y = y < 0 ? n - 1 : y;
if (hf[x, y] != 0)
{
if (colown + 1 == n)
hf[row, 0] = i;
else
hf[row, colown + 1] = i;
colown = colown + 1;
}
else
{
hf[x, y] = i;
row = x; colown = y;
}
}
x = Weishu(n);//取n*n位数
//输出幻方
for (int k = 0; k < n; k++)
for (int m = 0; m <= n; m++)
{
if (m == n)
{
System.Console.WriteLine();
break;
}
System.Console.Write(Geshihua(hf[k, m], x) + " ");
}
Console.ReadKey();
}
/// <summary>
/// 计算n*n位数
/// </summary>
/// <param name="n">阶数</param>
/// <returns>最大位数</returns>
public static int Weishu(int n)
{
return (n * n).ToString().Length;
}
/// <summary>
/// 格式化输出数
/// </summary>
/// <param name="geshihua">输出数</param>
/// <param name="l">最大位数</param>
/// <returns>格式化后的数</returns>
public static string Geshihua(int geshihua, int l)
{
return geshihua.ToString().PadLeft(l, '0');
}
}
}
已经了解算法的规律 初始化不太明白 幻方里面 for循环里面 x=row-1 y=colown-1这里不明白 还有下面的也不懂 希望大神给添加注释
1、将“1”放在第一行中间一列;
2、从“2”开始直到n*n止各数依次按下列规则存放:每一个数存放的行比前一个数
的行数减1,列数加1;
3、如果上一数的行数为1,则下一个数的行数为n(指最下一行);
4、当上一个数的列数为n时,下一个数的列数应为1,行数减1;
5、如果按上面规则确定的位置上已有数,或上一个数是第1行第n列时,则把下一个
数放在上一个数的下面。