【发布时间】:2014-02-26 07:35:00
【问题描述】:
我需要帮助调试和完成一个程序,该程序将:读取具有相同行数和每行上相同数量整数值的文件(这将是一个 n x n 矩阵)。程序应确定矩阵是否为幻方。 魔方示例:“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;
}
}
}
}
}
【问题讨论】:
-
为什么这个程序没有做你想做的事? (以及什么是“魔方”?)如果您能更清楚地说明您的问题,我们将更容易为您提供帮助。
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
魔方是 n×n 的矩阵(行数和列数相同),当您添加一行或一列(包括两条对角线)时,它会给您相同的答案或数字示例:[8,1,6] [3,5,7] [4,9,2]
-
魔方可能意味着每一行和每一列的总和,也许对角线是相同的(这里是 15)。因此,只需为这些条件添加测试即可。
-
@TomasLycken 当我运行程序时它给了我一些错误,我不知道我缺少什么部分,因为我是 C# 新手
标签: c# arrays type-2-dimension magic-square