[英]C++ generating a pascal triangle, wrong output
I have a problem with generating a pascal triangle in c++, same algorithm works good in java and in c++ it only works for the first two numbers of every line of the triangle in any other it generates way to big numbers. 我在c ++中生成一个Pascal三角形时遇到问题,相同的算法在Java中效果很好,在c ++中,它仅适用于该三角形每一行的前两个数字,而在生成大数的任何其他方式中均如此。 For example in java it generates: 1 5 10 10 5 1 and in C++: 1 5 1233124 1241241585 32523523500 etc Here is code:
例如,在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;
}
See if initializing the tab
array helps: 查看初始化
tab
数组是否有帮助:
tab = new int[n+1]();
tab = new int [n + 1]();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.