首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >帕斯卡三角函数

帕斯卡三角函数
EN

Stack Overflow用户
提问于 2021-11-17 18:56:01
回答 2查看 134关注 0票数 2

我试图编写一个函数,打印出Pascal的三角形,直到用户输入的步骤。该程序一直工作到第5步,并打印出0 1 4 0 4 1 0而不是预期的0 1 4 6 1 0。它从另一个列表中获取两个值,它们当时都是3,并添加它们,因此我不确定如何将它们更改为0。代码:

代码语言:javascript
复制
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));
    }
  }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-17 19:25:14

如果您想打印Pascal三角形逐行,则只需在计算进程中的next行(小提琴)时循环即可

代码:

代码语言:javascript
复制
    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));
      }
    }

演示:

代码语言:javascript
复制
PascalTri(10);

结果:

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2021-11-17 19:27:07

这也让我困惑了一段时间。然后,我意识到foreach中的一行代码是错误的。

TriList.Add(TempTriListj);

它应该是:

TriList.Add(j);

变量"j“不是索引,而是数组值本身。一旦你做出了改变,一切都会成功的。

如果使用递归方法,这段代码可能会安排得更好,但是既然您的代码已经工作了(现在),我将保留它。进行这种更改来使用递归可能是困难的,而且远远超出了这个问题的范围。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70010055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档