2015-01-21 348 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