我正在嘗試撰寫一個函式來列印出帕斯卡三角形直到用戶輸入的步驟。該程式一直運行到第 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));
}
}
uj5u.com熱心網友回復:
如果你想一行一行地列印Pascal Triangle,你可以在計算next程序中的行時回圈(小提琴)
代碼:
static void PascalTri(int rowsToPrint) {
// 1st current line
int[] current = new int[] { 0, 1, 0 };
Console.WriteLine(string.Join(" ", current));
// we compute all the other lines in a simple loop
for (int r = 1; r < rowsToPrint; r) {
// next line is 1 number longer than current
int[] next = new int[current.Length 1];
// compute next line items
for (int c = 0; c < current.Length - 1; c)
next[c 1] = current[c] current[c 1];
// after computation, next line becomes current one
current = next;
// finally, we print the line
Console.WriteLine(string.Join(" ", current));
}
}
演示:
PascalTri(10);
結果:
0 1 0
0 1 1 0
0 1 2 1 0
0 1 3 3 1 0
0 1 4 6 4 1 0
0 1 5 10 10 5 1 0
0 1 6 15 20 15 6 1 0
0 1 7 21 35 35 21 7 1 0
0 1 8 28 56 70 56 28 8 1 0
0 1 9 36 84 126 126 84 36 9 1 0
uj5u.com熱心網友回復:
這也讓我難住了一段時間。然后我意識到你的一行代碼foreach是錯誤的。
TriList.Add(TempTriList[j]);
它應該是:
TriList.Add(j);
變數“j”不是索引,而是陣列值本身。一旦你做出改變,一切都會奏效。
如果使用遞回方法,此代碼可能會得到更好的安排,但由于您的作業(現在),我會保留它。使用遞回進行更改可能很困難,并且遠遠超出了這個問題的范圍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359104.html
