C#程序开发金字塔,使用for循环

时间:2014-03-27 13:07:38

标签: c#

我可能错过了一些东西,但我找不到解决这个简单问题的方法..

我想写一个要求正整数的短代码,然后用FOR语句打印出金字塔,f.ex

Height: 0
Height: 4
   *
  ***
 *****
*******

这是代码本身

using System; 

namespace starpyramid
{ 
    class program 
    { 
        static void Main() 
        { 
            Veryfy:
            Console.Write("Height: "); 
            int i = int.Parse(Console.ReadLine());
            if(i>0)
            {
            goto main;
            }
            else
                {
            goto Verify;
            }   

        main:
            for (int h = 1; h< luku1;h++) // main loop for the lines
                {
                for (int s = 1; s < luku1; s++) //for spaces before the stars
                    {
                        if (s == h)
                        {
                        break;
                        }
                        Console.Write(" ");
                    }
                Console.Write("*\n");
                }
    }   
    } 
}

也许有人可以帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

它的工作完美,

using System; 

namespace starpyramid
{ 
    class program 
    { 
        static void Main() 
        { 
            Console.Write("Height: "); 
            int i = int.Parse(Console.ReadLine());
            if(i>0)
            {
            goto main;
            }
            else
            {
                Main();
            }   

            main:
            Console.Write("\n");
            for (int h = 1; h<= i;h++) // main loop for the lines
            {
                for (int s = h; s <= i; s++) //for spaces before the stars
                {
                    Console.Write(" ");
                }
                for(int j=1; j<(h*2); j=j+2)
                {
                    Console.Write("*");
                }
            Console.Write("\n");
            }
    }   
    } 
}

但没有goto程序也可以看到,

using System; 

namespace starpyramid
{ 
    class program 
    { 
        static void Main() 
        { 
            Console.Write("Height: "); 
            int i = int.Parse(Console.ReadLine());
            Console.Write("\n");
            for (int h = 1; h<= i;h++) // main loop for the lines
            {
                for (int s = h; s <= i; s++) //for spaces before the stars
                {
                    Console.Write(" ");
                }
                for(int j=1; j<(h*2); j=j+2)
                {
                    Console.Write("*");
                }
            Console.Write("\n");
            }
    }   
    } 
}