简体   繁体   English

无法理解Pascal Triangle for C ++中的这一行

[英]Can't Understand this line in Pascal's Triangle for C++

I have to write a code that generates a pascal's triangle with 12 rows. 我必须编写一个代码,生成具有12行的帕斯卡三角形。

I've written everything on my own except one part, That's the formula we use to generate numbers. 除了一个部分,我已经自己写了所有东西,这就是我们用来生成数字的公式。 And the problem is I don't understand what's the connection between our counters and generated numbers (since we're using our counters.). 问题是我不了解我们的计数器和生成的数字之间有什么联系(因为我们使用的是计数器)。

#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;
}

Here's the problem: 这是问题所在:

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

Can someone please explain how did the author came up with the idea of using these variables and how it works fine? 有人可以解释一下作者是如何提出使用这些变量的想法,以及它如何工作的吗?

This works because Pascal's triangle can be represented with binomial coefficients : 这是可行的,因为Pascal的三角形可以用二项式系数表示:

在此处输入图片说明

This formula in your code is based on the fact that, on the same n-index (in the pascal's triangle case, same line), in order to get the next element (k -> k+1), we need to multiply the current value by (nk)/(k+1): 您的代码中的此公式基于以下事实:在相同的n索引(在帕斯卡三角形的情况下,同一行)上,为了获得下一个元素(k-> k + 1),我们需要将当前值乘(nk)/(k + 1):

在此处输入图片说明

It's fairly easy to prove if you want to convince yourself about that. 如果您想说服自己,这很容易证明。 So you can get the next value from the previous one with this operation. 因此,您可以通过此操作从上一个值中获取下一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM