c++ - C++ 中的嵌套 For 循环三角形

标签 c++ for-loop

我正在尝试编写一个打印出此模式的嵌套 for 循环:

x
xxx
xxxxx
xxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxx
xxxxx
xxx
x

但是,我不知道如何使该列比最后一个多两颗星。

这是我目前的代码:

#include <iostream>
using namespace std;

int main()
{
    for(int r = 1; r <= 5; r++)
    {
        for(int c = 1; c <= r; c++)
            cout << "*";
            cout<< endl;
    }
    for(int r1 = 5; r1 >= 1; r1--)
    {
        for(int c1 = 1; c1 <= r1; c1++)
            cout << "*";
            cout<< endl;
    }
    return 0;
}

如果有人能帮我解决这个问题,我将不胜感激。

最佳答案

你现在已经关闭了,内循环终止条件是错误的。 观察到当行索引为 1,2,3,4,5 时,您需要打印 1,3,5,7,9 *。所以要打印的*个数是:2*rowIndex -1

for(int r = 1; r <= 5; r++){
    for(int c = 1; c <= 2*r -1; c++)
                   //^^^Here is the diff
             cout << "*";
        cout<< endl;
}
for(int r1 = 5; r1 >= 1; r1--){
        for(int c1 = 1; c1 <= 2*r1 -1; c1++)
                        //^^same here
                cout << "*";
        cout<< endl;
}
return 0;

您可以在此处观看现场演示:Print Triangle Star pattern

关于c++ - C++ 中的嵌套 For 循环三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22445629/

相关文章:

node.js - 如何循环对象并返回每个项目的 mongoDB 条目?

javascript - 在哪些情况下我应该使用 'while loops' 而不是 JavaScript 中的“for 循环”?

c++ - boost.python 不支持并行性?

c++ - 关于 std::type_info 中的反射扩展的一般感觉是什么?

c++ - 在动态分配的数组上使用 auto_ptr 的正确方法是什么?

c++ - 获取有关硬盘扇区原始数据更改的通知 - 文件更改通知

c++ - 使用 Boost 在 C++ 中并发

javascript - 如何向 div 添加 for 属性(如 labels for)?

python - 多个 for 循环以更 Pythonic 的方式相互依赖

Java 8 使用流重写一个复杂的 for 循环