c++ - 无法理解 Pascal's Triangle for C++ 中的这一行

标签 c++ pascals-triangle

我必须编写一个代码来生成一个 12 行的帕斯卡三角形。

我自己写了所有内容,除了一部分,那是我们用来生成数字的公式。问题是我不明白我们的计数器和生成的数字之间有什么联系(因为我们正在使用我们的计数器。)。

#include <iostream>
#include <string>

using namespace std;

int main() {
    const int rows=12;
    int padding, value, fxValue;

    for(int rowCounter=0; rowCounter<rows; rowCounter++)
    {
        fxValue=1;
        cout << string((rows-rowCounter)*6, ' ');

        for(int fxCounter=0; fxCounter<=rowCounter; fxCounter++)
        {
            value=fxValue;
            fxValue = fxValue*(rowCounter-fxCounter)/(fxCounter+1);

//          cout << "fxCounter: "<< fxCounter << endl
//               << "rowCounter: " << rowCounter << endl
//               << "fxCounter: " << fxCounter << endl
//               << "fxValue: " << fxValue << endl;

            padding=fxValue/10;

            if(padding==0) cout << value << string(11, ' ');
            else if(10>padding) cout << value << string(10, ' ');
            else if(padding>10) cout << value << string(9, ' ');
        }
        cout << endl;
    }
    return 0;
}

问题是:

fxValue = fxValue*(rowCounter-fxCounter)/(fxCounter+1);

谁能解释一下作者是如何想到使用这些变量的,以及它是如何工作的?

最佳答案

之所以可行,是因为帕斯卡三角形可以用二项式系数表示:

enter image description here

您代码中的这个公式基于这样一个事实,即在相同的 n-index 上(在 pascal 的三角形情况下,同一行),为了获得下一个元素 (k -> k+1),我们需要将当前值乘以 (n-k)/(k+1):

enter image description here

如果您想说服自己,证明起来相当容易。 因此,您可以通过此操作从前一个值中获取下一个值。

关于c++ - 无法理解 Pascal's Triangle for C++ 中的这一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27796415/

相关文章:

c++ - 不使用 for/while 循环的 Pascal 三角形计算

c++ - 关于对齐存储和普通可复制/可破坏类型

c++ - 内存相关崩溃: 3 Dimensional Array in Cocos2d Game

c++ - Visual Studio 2017 Linux远程调试(gdbserver)

c++ - 编译器无法推断出要返回哪种模板类型

java - 帕斯卡三角形正确格式化java

c++ - 带有类getter函数的奇怪输出C++

haskell - 在 Haskell 中打印 Pascal 的三角形

c - 帕斯卡三角返回无意义的值

python - 如何在Python中找到帕斯卡三角形的特定行?