static void Main(string[] args)
{
int rowIn = 0;
int[][] parts2 = new int[15][];//jagged output Array
//The txt-file has 1 number in the top line and every next line has 1 number more, all seperated by a space
foreach (string line in File.ReadAllLines("inputProblem18.txt"))//put the txt file in the same directory as the exe file
{
int columnIn = 0;
string[] parts = line.Split(' ');
int[] nums = new int[parts.Length];
foreach (string part in parts)
{
nums[columnIn] = Int32.Parse(parts[columnIn]);
parts2[rowIn] = nums;//fill the jagged output array
Console.Write(nums[columnIn] + " ");
columnIn++;
}
Console.WriteLine();
rowIn++;
}
for (int rowOut = 14; rowOut >= 1; rowOut--)
{
for (int columnOut = rowOut-1; columnOut >= 0; columnOut--)
{
parts2[rowOut - 1][columnOut] += Math.Max(parts2[rowOut][columnOut], parts2[rowOut][columnOut + 1]);
Console.Write(parts2[rowOut - 1][columnOut] + " ");//I got the answere here
Console.Write(rowOut - 1 + " " + columnOut + " ");
}
Console.WriteLine();
}
// The line below is causing me the error
Console.WriteLine("The greatest sum from top to bottom is: {1}", parts2[0][0]);
Console.ReadKey();
}
我正在研究Euler项目,这是一个不错的网站,存在很多编程问题。我第一次在生活中使用锯齿状的数组:-),所以我认为我不太了解它是否退出。
我想显示答案,即文件末尾[0] [0]处锯齿状数组的值,但出现错误,我不知道为什么。在for循环中,我得到了正确的值。
这是错误消息:
索引(从零开始)必须大于或等于零且小于参数列表的大小。
答案 0 :(得分:0)
您正在使用{1}
显示parts2[0][0]
。由于这是第一个变量,因此应为{0}
,而不是1。参数列表可以视为数组,并从索引0开始。
更改此内容:
// Notice this ----------------------------------------v
Console.WriteLine("The greatest sum from top to bottom is: {1}", parts2[0][0]);
// Boom !
// Index (zero based) must be greater than or equal
// to zero and less than the size of the argument list.
对此:
// Notice this ----------------------------------------v
Console.WriteLine("The greatest sum from top to bottom is: {0}", parts2[0][0]);