我需要一些关于在 C++ 中打印 Pascal 三角形的程序的帮助。我需要这样的间距:
How many rows: 4
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
但它看起来像这样:
Enter a number of rows: 4
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
我的代码是:
#include <iostream>
#include <iomanip>
using namespace std;
int combinations (int n, int k) {
if (k == 0 || k == n) {
return 1;
}
else {
return combinations(n-1,k-1) + combinations(n-1,k);
}
}
int main ( ) {
int rows;
cout << "Enter a number of rows: ";
cin >> rows;
for(int r = 0; r < rows+1; r++) {
cout << " " << "1";
for(int c = 1; c < r+1; c++) {
cout << " " << combinations(r, c) << ' ';
}
cout << endl;
}
}
谁能帮我调整一下间距?
最佳答案
看起来主要区别在于前面的间距,您可以保持不变但不应该:
cout << " " << "1";
相反,如果您计算所需输出中前面的空格数,您会注意到它每行减少 3 个。所以:
for (int s = 0; s < 3 * (rows - r) + 1; ++s) {
cout << ' ';
}
cout << '1';
或者只是:
cout << std::string(3 * (rows - r) + 1, ' ');
打印每个元素也不正确。而不是:
cout << " " << combinations(r, c) << ' ';
你想要这个:(开头五个空格,结尾没有空格):
cout << " " << combinations(r, c);
或者,为了清楚起见:
cout << std::string(5, ' ') << combinations(r, c);
然而,这些都不能处理多位数的值,所以真正正确的做法是使用 setw
:
cout << setw(3 * (rows - r) + 1) << '1';
// ..
cout << setw(6) << combinations(r, c);
关于c++ - 帕斯卡三角形程序的间距 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057649/