作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个打印出此模式的嵌套 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/
我是一名优秀的程序员,十分优秀!