gpt4 book ai didi

c++ - 使用 for 循环创建平行四边形

转载 作者:行者123 更新时间:2023-11-27 22:48:54 31 4
gpt4 key购买 nike

你好,我正在尝试创建一个平行四边形,但到目前为止我遇到了一些麻烦

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';
}

live example

话虽如此,这不是很可读,我宁愿选择:(或 Lassie 的回答)

string nstars(n, '*');
for(int i = 0; i < n; ++i) {
cout << string(i, ' ') << nstars << '\n';
}

live example

这将创建一个 std::stringi 个空格和 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com