C++嵌套环形
C++ nested loop shape
我一直在使用嵌套循环来创建某种形状来制作自己的C++程序。我最近的项目是创建一个看起来像这样的形状
*
**
***
****
*****
*****
****
***
**
*
但是我写了一个程序,给了我一个结果
*
**
***
****
*****
*****
****
***
**
*
这也是我的代码
#include <iostream>
using namespace std;
void main(){
//displays a top triangle going from 1 - 5(*)
for (int i = 0; i <= 5; i++){
for (int j = 0; j <= i; j++){
cout << "*";
}
cout << endl;
}
//displays a bottom to top triangle 5 - 1(*)
for (int k = 0; k <= 5; k++){
for (int l = 5; l >= k; l--){
cout << "*";
}
cout << endl;
}
system("pause");
}
这会很有帮助,谢谢:)
在第二个循环中,您需要:
std::string spc = " "; // add #include <string> at the top of the file
for (int k = 0; k <= 5; k++) {
cout << spc;
for (int l = 5; l >= k; l--){
cout << "*";
}
spc += " ";
cout << endl;
}
在第二个嵌套循环中,不打印空格。
有一个三个空格的字符串,然后在每次运行内部循环后,向其附加另一个空格并打印它:
spc = " ";
for (int k = 0; k <= 5; k++){
cout << spc;
for (int l = 5; l >= k; l--){
cout << "*";
}
spc += " ";
cout << endl;
}
你可以试试这个: http://ideone.com/hdxPQ7
#include <iostream>
using namespace std;
int main()
{
int i, j, k;
for (i=0; i<5; i++){
for (j=0; j<i+1; j++){
cout << "*";
}
cout << endl;
}
for (i=0; i<5; i++){
for (j=0; j<i+1; j++){
cout << " ";
}
for (k=5; k>i+1; k--){
cout << "*";
}
cout << endl;
}
return 0;
}
这是它的输出:
*
**
***
****
*****
****
***
**
*
希望这有帮助(需要优化)。
void printChars(int astrks, int spcs, bool bAstrkFirst)
{
if(bAstrkFirst)
{
for(int j = 0; j<astrks;j++)
{
std::cout<<"*";
}
for(int k = 0; k<spcs;k++)
{
std::cout<<" ";
}
}
else
{
for(int k = 0; k<spcs;k++)
{
std::cout<<" ";
}
for(int j = 0; j<astrks;j++)
{
std::cout<<"*";
}
}
std::cout<<std::endl;
}
int main()
{
int astrk = 1, spc = 7;
for(int x = 0; x<5; x++)
{
printChars(astrk++, spc--, true);
}
for(int x = 0; x<5; x++)
{
printChars(--astrk, ++spc, false);
}
getchar();
return 0;
}
输出:
*
**
***
****
*****
*****
****
***
**
*
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 如何在嵌套类中正确使用友元声明?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray