2015-01-21 55 views
0

我需要一些帮助,用C++打印Pascal的三角形程序。我需要的间距看起来像这样:帕斯卡的三角形程序间距C++

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

有人可以帮我把间隔的权利?

+1

您提出问题的方式使您看起来像没有尝试解决特定问题。 – 2015-01-21 00:33:04

+0

我尝试了很多事情,但我无法弄清楚如何让它工作。例如,我尝试了<< setw的各种组合。 – Kelton2 2015-01-21 00:34:10

+0

我在过去为另一篇文章写了一个解决方案。你可以查看http://stackoverflow.com/questions/19898756/pascals-triangle-using-mainly-functions-in-c/ – Ares 2015-02-13 03:55:23

回答

1

貌似主要差别是间隔在前面,你有恒定的,但不应该是:

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); 
+0

这几乎是正确的(我看到我犯了我的错误),但它仍然左侧太多空间。这是像添加一个setw一样简单吗? – Kelton2 2015-01-21 00:38:17

+0

@ Kelton2其实'setw'会更好 - 因为它可以处理多个数字。更新。 – Barry 2015-01-21 00:42:06

+0

它仍然在左边太多地方。 – Kelton2 2015-01-21 00:47:18