[英]How to display distances between towns C# using 2D arrays
I have a task to display the distances between towns using 2D arrays.我的任务是使用二维数组显示城镇之间的距离。 With the table I have already got with my code what would I add to make it look like the desired output shown below.
有了表格,我的代码已经有了,我将添加什么以使其看起来像下面显示的所需输出。 The distances between towns need to be a 2D array.
城镇之间的距离需要是一个二维数组。 Any help is appreciated.
任何帮助表示赞赏。 Desired Output Here is the code I already have that I need to add to:
所需的输出这是我已经拥有的需要添加的代码:
[1]String[] Towns = new String[20];
int[,] Distance = new int[10, 10];
Towns[0] = "Castletown";
Towns[1] = "Douglas";
Towns[2] = "Peel";
Towns[3] = "Ramsey";
Distance[0, 0] = 0;
Distance[0, 1] = 11;
Distance[0, 2] = 12;
int NumberOfTowns = 4;
Console.WriteLine("\t" + string.Join("\t", Towns)); // Print towns row accross
for (int k = 0; k < NumberOfTowns; k++)
{
Console.Write(Towns[k].PadLeft(3) + "\t"); // Print towns row down
Console.WriteLine();
}
Console.ReadKey();
Well you are missing the distance between 0 Castletown and 3 Ramsey so you definitely need Distance[0, 3] = 26;好吧,您错过了 0 Castletown 和 3 Ramsey 之间的距离,因此您肯定需要 Distance[0, 3] = 26;
Also if we have one axis than the distance between Douglas and Peel should be 1 not 10 like in the desired outcome picture and between Ramsey and Peel it should be 14 not 15 but maybe I misunderstood the problem :D let me know if I did此外,如果我们有一个轴,那么道格拉斯和皮尔之间的距离应该是 1 而不是 10,就像在期望的结果图片中一样,拉姆齐和皮尔之间的距离应该是 14 而不是 15,但也许我误解了这个问题:D 如果我这样做了,请告诉我
I would approach it a little bit different, I think its easier if you use a dictionary instead of the arrays but you can do the same with arrays as well.我会有点不同,我认为如果你使用字典而不是数组会更容易,但你也可以对数组做同样的事情。 My code looks something like this:
我的代码看起来像这样:
class Program
{
static void Main(string[] args)
{
//init dictionary
var Towns = new Dictionary<string, int>()
{
{ "Castletown" , 0 },
{ "Douglas" , 11},
{ "Peel " , 12},
{ "Ramsey", 26}
};
//print header
Console.Write("\t");
foreach (var town in Towns)
{
Console.Write("\t" + town.Key);
}
Console.WriteLine();
//print rows
foreach (var town in Towns)
{
Console.Write(town.Key+ " " + "\t"); // print town name
foreach (var toown in Towns)//print distances
{
Console.Write(Math.Abs(town.Value-toown.Value) + "\t") ;
}
Console.WriteLine();
}
}
}
Naming could be better and you might need to tweek the spacing but it does what you wanted.命名可能会更好,您可能需要调整间距,但它可以满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.