如果输入是 6,我希望金字塔看起来像这样
0
12
345
6789
01234
567890
这是我的代码
void HalfPyramid(int num)
{
for (int a=0; a<num; a++)
{
for (int b=0; b<num-a; b++)
{
cout << " ";
}
for (int c=0; c<a; c++)
{
cout << a;
}
cout << endl;
}
}
我得到了
1
22
333
4444
55555
不确定如何显示数字始终在增加,我尝试输出 a
和 a+1
。
最佳答案
您需要另一个变量。该变量需要从 0 开始并在每次打印时递增。然后,由于您需要在打印 9 后返回到 0,因此我们将使用取模运算符将输出限制在 [0, 9] 的范围内。有了你得到的一切
void HalfPyramid(int num)
{
int output = 0;
for (int a=1; a<num+1; a++)
{
for (int b=0; b<num-a; b++)
{
cout << " ";
}
for (int c=0; c<a; c++)
{
cout << output++ % 10;
}
cout << endl;
}
}
关于c++ - 打印半金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42838162/