【发布时间】:2021-12-28 18:21:28
【问题描述】:
我正在尝试编写一个函数来打印出 帕斯卡三角形 直到用户输入的步骤。该程序一直运行到第 5 步,并打印出 0 1 4 0 4 1 0 而不是预期的 0 1 4 6 1 0。它从另一个列表中获取两个值,当时都是3,然后添加它们,所以我不确定它如何更改为0。
代码:
static void PascalsTri(int input)
{
//Declare lists starting at 0 1 0
int counter = 0;
int[] start = { 0, 1, 0 };
List<int> TriList = new List<int>(start);
List<int> TempTriList = new List<int>();
//Check if input is possible
if(input < 1)
{
return;
}
//Write starting list to console
Console.WriteLine(string.Join(" ", TriList));
//Run the function as many times as the user input
for(int i = 1; i < input; i++)
{
//Start off with the first two digits
TempTriList.Add(0);
TempTriList.Add(1);
//Loop through writing the rule for as many numbers as there are
while(counter < i)
{
//Takes the previous number and adds it to the correlating number
TempTriList.Insert(counter+1, TriList[counter] + TriList[counter+1]);
counter++;
}
TempTriList.Add(0);
TriList.Clear();
//Records the output in the permanent list, and prints it to the console
foreach(int j in TempTriList)
{
TriList.Add(TempTriList[j]);
}
TempTriList.Clear();
counter = 0;
Console.WriteLine(string.Join(" ", TriList));
}
}
【问题讨论】: