我需要帮助调试和完成一个程序,该程序将:读取每行具有相同行数和相同整数值的文件(这将是 anxn 矩阵)。程序应确定矩阵是否为幻方。幻方示例:“ms.txt”8,1,6;3,5,7;4,9,2
我的代码(正在进行中),您的帮助将不胜感激
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace MagicSquare
{
class Program
{
static void Main(string[] args)
{
int[,]S;
string line; //to hold one line of file
string[] token; //to hold each token in line
char[] separator = { ',' };
int N;
//open file
try
{
using (StreamReader sr = new StreamReader("..\\..\\ms.txt"))
{
line = sr.ReadLine();
token = line.Split(separator);
N = token.Count();
S = new int[N, N];
for (int i = 0; i < N; i++)
S[0, i] = Convert.ToInt32(token[i]);
for (int r = 1; r < N; r++)
{
line = sr.ReadLine();
token = line.Split(separator);
for (int c = 0; c < N; c++)
S[r, c] = Convert.ToInt32(token[c]);
}
sr.Close();
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
//find Magic Number
int magic = 0;
for (int i = 0; i < N; i++)
magic += S[i, i];
int sum = 0;
for (int i=0;i<N;i++)
sum += S[i,N -1-i];
if (magic!=sum)
{
Console.Write("Not Magic");
return;
}
//check each column
for (int c=0;c<N;c++)
{
int sum1 =0;
for (int r=0;r<N;r++)
sum1 += S[r,c];
if (sum1!=magic)
{
Console.WriteLine("Not magic");
return;
}
}
}
}
}