简体   繁体   English

在Pascal的三角形程序上间隔C ++

[英]Spacing on a pascal's triangle program c++

I need some help with a program that prints Pascal's Triangle in c++. 我需要一些在c ++中打印Pascal三角形的程序的帮助。 I need the spacing to look like this: 我需要间距看起来像这样:

How many rows: 4
             1
          1     1
       1     2     1
    1     3     3     1
 1     4     6     4     1

but instead it looks like this: 但是它看起来像这样:

Enter a number of rows: 4
        1
        1           1
        1           2            1
        1           3            3            1
        1           4            6            4            1

My code is: 我的代码是:

#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;
    }
}

Can someone help me get the spacing right? 有人可以帮助我调整间距吗?

Looks like the main difference is the spacing at the front, which you have constant but shouldn't be: 看起来主要的区别是前面的间距,您可以保持不变,但不应这样:

cout << "            " << "1";

Instead, if you count the number of spaces at the front in your desired output, you'll notice that it decreases by 3 every row. 相反,如果您在期望的输出中计算前面的空格数,则会注意到它每行减少3。 So: 所以:

for (int s = 0; s < 3 * (rows - r) + 1; ++s) {
    cout << ' ';
}
cout << '1';

Or just: 要不就:

cout << std::string(3 * (rows - r) + 1, ' ');

Also printing each element is incorrect. 同样,打印每个元素都不正确。 Instead of: 代替:

cout << "           " << combinations(r, c) << ' ';

You want this: (five spaces in beginning, no spaces at end): 您需要这样:(开头有五个空格,结尾没有空格):

cout << "     " << combinations(r, c);

Or, for clarity: 或者,为清楚起见:

cout << std::string(5, ' ') << combinations(r, c);

None of that, however, would handle multiple-digit values, so really the right thing to do is use setw : 但是,这些都不能处理多位数的值,因此,正确的做法是使用setw

cout << setw(3 * (rows - r) + 1) << '1';
// ..
cout << setw(6) << combinations(r, c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM