所以我一直在尝试构建一个看起来像(https://snag.gy/4yW5hr.jpg)的完整金字塔,但我只能正确地将金字塔的右侧打印出来,我如何让程序显示完整的金字塔为如上面的截图所示?谢谢你的帮助。
#include <iostream>
using namespace std;
int main()
{
int r,n,s;
cout<<"Enter the desired number of rows:";
cin>>n;
//1st triangle
for(s=1; s<=n; s++)
{
for(r=1; r<=s; r++)
{
cout<< r <<" ";
}
cout<< endl;
}
return 0;
}
Example 7与您的问题相关。如果你愿意,你可以用足够的空间设置width
和std::cout
的fill
。
下面是一个代码示例,不一定是最有效的代码示例:
#include <iostream>
std::ostream &print(std::ostream &output, const int N, bool reverse) {
if (reverse)
for (int n = N; n > 1; n--)
output << n << (n > 9 ? " " : " ");
else
for (int n = 2; n <= N; n++)
output << (n > 9 ? " " : " ") << n;
return output;
}
int main(int argc, char *argv[]) {
int nrows;
std::cout << "Enter number of rows (1-15): ";
std::cin >> nrows;
if (nrows < 1 || nrows > 15) {
std::cerr << "Number of rows is not in [1,15].\n";
return 1;
}
for (int row = 1; row <= nrows; row++) {
std::cout.width((nrows - row + 1) * 3);
std::cout.fill(' ');
print(std::cout, row, true) << 1;
print(std::cout, row, false) << '\n';
}
return 0;
}
这给出了类似的东西:
~/Desktop ./a.out
Enter number of rows (1-15): 4
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4