你好,我正在尝试创建一个平行四边形,但到目前为止我遇到了一些麻烦
void stars(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > j) {
cout << " ";
}
else cout << "*";
}
cout << endl;
}
}
所以 stars(7) 打印
*******
******
*****
****
***
**
*
但是我需要它像这样打印
*******
*******
*******
*******
*******
*******
*******
我的功能是正确地移动空间,但它也减少了星星的数量,我怎样才能继续移动星星而不丢失星星的数量?
最佳答案
不要让打印星号有条件。打印 i
个空格,然后打印 n
个星号。
for(int i = 0; i < n; ++i) {
for(int j = 0; j < i; ++j) {
cout << ' ';
}
for(int j = 0; j < n; ++j) {
cout << '*';
}
cout << '\n';
}
话虽如此,这不是很可读,我宁愿选择:(或 Lassie 的回答)
string nstars(n, '*');
for(int i = 0; i < n; ++i) {
cout << string(i, ' ') << nstars << '\n';
}
这将创建一个 std::string
的 i
个空格和 n
个星号。它带有额外分配的成本,但可读性通常更重要,尤其是对于小型玩具项目。
如果您更喜欢 stdlib 算法:
for(int i = 0; i < n; ++i) {
fill_n(ostream_iterator<char>(cout), i, ' ');
fill_n(ostream_iterator<char>(cout), n, '*');
cout << '\n';
}
我不认为这应该比第一个循环更糟糕,但对于新手来说它可能看起来很可怕。
关于c++ - 使用 for 循环创建平行四边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39811002/