C++嵌套环形

C++ nested loop shape

本文关键字:嵌套 C++      更新时间:2023-10-16

我一直在使用嵌套循环来创建某种形状来制作自己的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;
}

输出:

*
**
***
****
*****
   *****
    ****
     ***
      **
       *