这是我的第一个问题,所以如果我做错了什么,请不要生我的气。我必须制作一个 C++ 程序,它从选定的行返回一个元素,例如:
Triangle 4 0 1 2 3
应该返回元素:0, 1, 2 and 3
从第 4 行开始,但它返回奇怪的东西,比如:
Element 0: 1
Element 1: 10179988
Element 2: 50792126
Element 3: 91425820
我不知道为什么
这是我的代码:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Pascal {
private:
int *tab;
public:
Pascal(int n) throw(string) {
if (n < 0)
throw (string)"";
tab = new int[n+1];
for(int i = 1; i <= n; i++) {
for(int k = i; k >=0; k--) {
if (k - 1 >= 0)
tab[k] += tab[k-1];
else
tab[k] = 1;
}
}
};
int element(int m) {
return tab[m];
}
};
int main(int argc, char* argv[]) {
int n = 0, m = 0, elem = 0;
try {
n = strtol(argv[1], NULL, 0);
Pascal *row;
for(int i = 2; i < argc; i++) {
try {
m = strtol(argv[i], NULL, 0);
row = new Pascal(n+1);
if (m <= n && m >= 0) {
elem = row->element(m);
cout << "Element " << m << ": "<< elem << endl;
} else
cout << m << " - bad element index" << endl;
} catch (string ex) {
cout << argv[i] << " - bad element index!" << endl;
continue;
}
delete[] row;
}
} catch (string e) {
cout << argv[1] << " - bad row index!" << endl;
return 0;
}
}
我会很感激任何答案