[英]Spacing on a pascal's triangle program c++
我需要一些在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.