C 星形图案具有高度和宽度

c++ star pattern with height and width

本文关键字:高度      更新时间:2023-10-16

我想在C 中发展以下模式。

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

 printf("Enter trunk height: ");
 scanf("%d", &trunk_height);
 printf("Enter trunk width: ");
 scanf("%d", &trunk_width);
 printf("Enter leaves width: ");
 scanf("%d", &leaves_width);

毛部高度为9。
毛宽=5。
叶宽为11。

我编写一些代码,但不起作用。我的问题是如何检测毛刺的高度以及如何编写从用户获取信息的代码。

int main()
{
    int i, j;
    int x = 5;
    int y = 1;
    for(j = 1; j <= 5; j++)
    {
       for(i = 1; i <= x; i++)
       {
          cout << " ";
       }
       x--;
       for(i = 1; i <= y; i++)
       {
          cout << "*";
       }
       y += 2;
       cout << endl;
   }
}

尝试以下代码:

#include<iostream>
using namespace std;
int main() {
    int height = 9, width = 5, leave = 11;
    // Print tree
    int stars = 1;
    for(int row = (leave + 2 - 1)/2; row >= 1  ; row--){
        cout<<string(row, ' ')<<string(stars, '*')<<endl;
        stars += 2;
    }
    // Print trunk
    int pos = (leave - width )/2 +1;
    for(int row = 0; row<height; row++){
        cout<<string(pos, ' ')<<string(width, '*')<<endl;
    }
}

输出:

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

IDEONE链接