简体   繁体   English

如何在 C++ 中打印下面的三角形图案?

[英]How do I print the triangle pattern below in C++?

三角形输出图像

#include <iostream>
using namespace std;

int main(){

    int rows, i, j, space;

    cout << "Enter number of rows: ";
    cin >> rows;

    for(i = rows; i >= 1; i--)
    {
       //for loop to put space
       for(space = i; space < rows; space++)
          cout << " ";
       //for loop for displaying star
       for(j = 1; j <= (1 * i ); j++)
          cout << "* ";

       cout << "\n";
    }


    for(i = 2; i <= rows; i++)
    {
       //for loop for displaying space
       for(space = i; space <= rows; space++)
       {
          cout << " ";
       }
       //for loop to display star equal to row number
       for(j = 1; j <= (1 * i ); j++)
       {
          cout << "*";
       }

       cout << "\n";
    }

    return 0;
}

I have used the code above and although the inverted pyramid above is correct, the pyramid below is not spaced properly..我已经使用了上面的代码,虽然上面的倒金字塔是正确的,但下面的金字塔没有正确间隔..

for (i = 2; i <= rows; i++)
{
    for (space = i+1; space <= rows; space++)    //need to initialize space with i+1
    {
        cout << " ";
    }
    for (j = 1; j <= (1 * i); j++)
    {
        cout << "* ";    //Need to add an extra space
    }

    cout << "\n";
}

This is the 2nd for loop, which has small modification.这是第二个 for 循环,有小的修改。 Hope it solves you issue.希望它能解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM