首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#中打印星形(*)直角三角形

在C#中打印星形(*)直角三角形
EN

Stack Overflow用户
提问于 2012-09-13 05:36:39
回答 3查看 18.1K关注 0票数 0

我已经用嵌套的for循环做到了这一点,但我还想知道如何用while循环做到这一点。我已经有这个了

代码语言:javascript
复制
 int j = 10;
     int k = 0;
     while (j > 0)
     {
        if (k <= j)
        {
           Console.Write("* ");
           Console.WriteLine();
        }
        j--;
     } Console.WriteLine();

它打印出一行星号(*)。我知道内部循环必须引用外部循环,但我不确定在while语句中如何做到这一点。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-13 05:58:37

这确实会产生类似于三角形的东西:

代码语言:javascript
复制
int x = 1;
int j = 10;
int k = 0;
while (j > 0)
{
    if (k <= j)
    {
       Console.Write("* ");
    }
    if (j >= 1)
    {
        int temp = x;
        while (temp >= 0)
        {
            Console.Write(" ");
            temp--;
        }
        x = x + 1;
        Console.Write("*");

     }
       Console.WriteLine();
       j--;
   }
   Console.WriteLine();
   double f = Math.Round(x * 1.5);
   while (f != 0)
   {
      Console.Write("*");
      f--;
   }
票数 1
EN

Stack Overflow用户

发布于 2012-09-13 05:49:18

for循环可以与while循环互换。

代码语言:javascript
复制
// Height and width of the triangle
var h = 8;
var w = 30;

// The iterator variables
var y = 1;
var x = 1;

// Print the tip of the triangle
Console.WriteLine("*");

y = 1;
while (y++ <h) {
    // Print the bit of left wall
    Console.Write("*");

    // Calculate length at this y-coordinate
    var l = (int) w*y/h;

    // Print the hypothenus bit
    x = 1;
    while (x++ <l-3) {
            Console.Write(" ");
    }
    Console.WriteLine("*");
}

// Now print the bottom edge
x = 0;
while (x++ <w) {
    Console.Write("*");
}

输出:

代码语言:javascript
复制
*
*   *
*       *
*           *
*              *
*                  *
*                      *
*                          *
******************************
票数 3
EN

Stack Overflow用户

发布于 2013-03-22 21:35:34

代码语言:javascript
复制
 class x
    {
        static void Main(string[] args)
        {
            int i, j;
            for ( i=0;i<10;i++)
            {
                for (j = 0; j < i; j++)
                    Console.Write("*");
                Console.WriteLine();
            }

        }

    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12396510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档