【发布时间】:2022-01-03 23:26:01
【问题描述】:
我想要一个模式,其中第一行的 n=4 有 4 颗星,第二行有 1 个空格和 3 颗星,第三行有 2 个空格和 2 颗星,依此类推。
****
***
**
*
代码,我试图解决这个问题。
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << endl;
int i = 1;
while (i <= n)
{
//Printing Spaces
int space = i - 1;
while (space)
{
cout << " ";
space++;
}
//Printing Stars
int j = 1;
while (j <= n)
{
cout << "*";
j++;
}
cout << endl;
i++;
}
return 0;
}
【问题讨论】:
-
int space = i - 1; while (space) { cout << " "; space++; }如果空格以正数开头,然后在循环内的空格上加 1,那么while (space)什么时候会是假的? (特别是因为滚动有符号整数是未定义的行为:stackoverflow.com/questions/16188263/…)
标签: c++ loops while-loop