c++ - 帕斯卡三角形程序的间距 C++

标签 c++ pascals-triangle

我需要一些关于在 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/

相关文章:

c - 如何将这个递归函数转换为迭代版本?

c++ - C++ 中的帕斯卡三角形

c++ - 具有来自同一类的回调的 Poco 计时器

android - Android Eclipse 项目中的 Qt C++ 库 : QSQLITE driver not loaded

python - 在 Python 中使用递归元组的 Pascal 三角形

PASCAL TRIANGLE 中数字的正确对齐

C++ 帕斯卡三角形

C++将数组直接传递给函数而不先对其进行初始化

c++ - 引用类型和文字类型

c++ - 在不同命名空间中将函数声明为内联友元