C ++生成一个pascal三角形,输出错误

时间:2014-03-15 12:13:22

标签: c++ pascals-triangle

我在c ++中生成一个pascal三角形有一个问题,同样的算法在java和c ++中运行良好它只适用于三角形的每一行的前两个数字,它生成大数字。例如,在java中它生成: 1 5 10 10 5 1和C ++:1 5 1233124 1241241585 32523523500等 这是代码:

#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Pascal {
private:
    int* tab;
    int prev1;
    int prev2;
    public:

    Pascal(int n) {
        tab = new int[n+1];
        prev1=0;
        prev2=0;

        for(int i = 0; i <= n; i++) {
            for(int k = 0; k <= i; k++) {
                if (k == 0) {
                    tab[k] = 1;
                    prev2 = 1;
                } else {
                    prev1 = tab[k-1] + tab[k];
                    tab[k-1] = prev2;
                    prev2 = prev1;
                }
            }
        }
    }

int wspolczynnik(int m) {
    return tab[m];
  }
 };

 int main (int argc, char* argv[]) {
    int n = 0, m = 0;

n = atoi(argv[1]);  // konwersja string na int

if (n >= 0)

    for (int i = 2; i < argc; i++) {
        Pascal *wiersz = new Pascal(n);
        m = atoi(argv[i]);


        int result = wiersz->wspolczynnik(m);

        if (m < 0 || m > n)
            cout << m << " - element poza zakresem" << endl;
        else
            cout << m << " : " << result << endl;

        delete[] wiersz;
    }
    return 0;
 }

1 个答案:

答案 0 :(得分:0)

查看初始化tab数组是否有帮助:

  

tab = new int [n + 1]();