使用pascal三角形打印二项式系数

时间:2015-03-12 10:39:41

标签: c++ syntax

问题是:

二项式系数是二项式幂的乘积的数值因子,例如(x + y) * n。对于 例如,(x + y) * 2 = 2 x + 2 x y + 2 y具有系数1 2 1。可以使用Pascal来计算二项式系数 三角:

三角形的每个新等级在末端都有1个;内部数字是它们上面两个数字的总和。 我必须编写一个程序,其中包含一个递归函数,用于生成幂n的二项式系数列表。 Pascal的三角技术。

这是代码。如果输入1 2 1为2,我需要输出x,但输出不正确。

#include <iostream>
using namespace std;
int pascal(int n, int x){
    if ((n==0) || (n==1) || (n==x))
        return 1;
    else
        return pascal(n, x-1) + pascal(n, x-1);
}
int main()
{
    int x;
    cout << "Input the number of which you want to print the binomial coefficients : ";
    cin >> x;
    int n = 0;
    for (int i=0; i<x; ++i)
        cout << pascal(n, x) << " ";
}

1 个答案:

答案 0 :(得分:1)

一个好的经验法则是,无论何时将变量传递给函数并且其值保持不变,都将其作为常量传递。然后像

那样发生错误
n=1

而不是

n==1

不可能发生,因为编译器不会允许它。

int pascal(const int n, const int x)
{
    if(n == 0 || n == 1 || x == 0 || x == n)
        return 1;
    return pascal(n-1, x-1) + pascal(n-1, x);
}

注意

const int n, const int x

而不是

int n, int x

在功能头中。

Output

int main()
{   
    for(int n=0;n<12;++n){
        std::cout << "n = " << n << ": ";
        for(int x=0;x<=n;++x){
            std::cout << pascal(n, x) << ' ';
        }
        std::cout << std::endl;
    }
    return 0;
}
相关问题