gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:53:52 25 4
gpt4 key购买 nike

我正在尝试编写一个打印出此模式的嵌套 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/

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