如何打印下面的星形图案

我无法得到这个答案:


*****

****

***

**

*

多维数组,嵌套 ( do..while, while, for)


char[,] stars = new char[5, 3];


for (int i = 0; i < 5; i++) 

{

    for(int x=0;x<3;x++)

    {

        stars[i,x]=char.Parse("*");


        Console.Write(stars[i, x]);

我想要获得 5 颗“*”星,然后在新行中获得 4 颗星,然后在新行中获得 3 颗星,然后在新行中获得 1 颗星


HUWWW
浏览 101回答 2
2回答

慕慕森

这里你需要了解背后的模式*。你的程序中的星形模式是,0st Line : 5 starts&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Considering starting index is 01st Line : 4 starts&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // starts = n starts - Line no. where n = 52nd Line : 3 starts3rd Line : 2 starts4th Line : 1 startsIE单行中的星星数量 = n 开始 - 行号 // 其中 n = 5所以你的代码看起来像,int n = 5;for (int i = 0; i < n; i++)&nbsp; &nbsp;&nbsp;{&nbsp; &nbsp; for (int j = 0; j < n - i; j++)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//^^^^^ n - i is key behind this * pattern&nbsp; &nbsp; &nbsp; &nbsp; Console.Write("*");&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; Console.WriteLine();&nbsp;&nbsp;}

慕少森

由于这不是关于数组索引或地址计算,而是关于实际的可数对象(星),所以我认为基于 1 的索引在这里更有意义。此外,星星的数量应该减少,因此倒数也更有意义:for (int numStars = 5; numStars >= 1; --numStars){&nbsp; &nbsp; for (int star = 1; star <= numStars; ++star)&nbsp; &nbsp; &nbsp; &nbsp; Console.Write("*");&nbsp; &nbsp; Console.WriteLine();}
打开App,查看更多内容
随时随地看视频慕课网APP