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

标签 c++ visual-c++

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

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/

相关文章:

c++ - 为什么在这里使用 static char const* 而不是字符串文字会有所不同?

windows - WinInet 与 WinHttp(服务或类似服务的进程)

c++ - 包含 .cpp 文件和 .h 文件(cpp 中的内容相同)的区别?

c++ - 使用 VC++ 编译 SQLite 时如何处理警告?

c++ - STL通过 map C++反向循环

c++ - 如何在 OpenCV 中操作 RGB 级别?

c++ - 苹果操作系统 : using detachNewThreadSelector method inside a C++ class method

c++ - 跨数据 block 的连续流计算

visual-c++ - ffmpeg lib中的函数avformat_open_input无法打开文件

c++ - 如何将 C++ 程序作为 Simulink block 运行?