以C++输出一个数字三角形

Output a triangle of numbers in C++

本文关键字:一个 数字 三角形 C++ 输出      更新时间:2023-10-16

我的任务是要求用户输入int,然后输出如下所示的"数字三角形"(在这种情况下,int等于5(。

0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0

但是,我为此任务编写的代码输出以下内容:

0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0

作为参考,这是我的代码:

#include <iostream>

using namespace std;
int main() {

int size;
cout << "Size: " << std::endl;
cin >> size;

for(int i = size; i >= 0; i--)
{
for(int j = 0; j <= i; j++)
{
if (j < i){
cout << j << " ";
}
else{
cout << j << " ";}

}
cout << endl;

}


return 0;
}

有人可以告诉我在我的程序中要更改什么以使其输出正确的三角形吗?提前谢谢。

您应该在行的开头而不是结尾打印空格。

for(int i = size; i >= 0; --i){
for(int j = 0; j < size-i; ++j){cout << "  ";} // spaces at the beginning
for(int j = 0; j <= i; ++j){
cout << j << " ";
}
cout << endl;
}