典型的格式化输出算法,用*组成的倒三角形

要求输出以下格式:
*******
  *****
    ***
      *
方法一:通过循环控制每一行空格和“*”的个数
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Class1
    {
        public static void Main()
        {
            int i, j, m, n;
            m = 0;
            n = 7;
//通过while循环控制行数
            while (m < 4)
            {
//每行空格的个数
                for (j = 0; j < m * 2; j++)
                {
                    Console.Write(” “);
                }
//每行“*”的个数
                for (i = 0; i < n; i++)
                {
                    Console.Write(“*”);
                }
                Console.Write(“/n”);
                m++;
                n -= 2;
            }
        }
    }
}
方法二:
使用Console.Write的格式控制,Console.Write(“{0,±10}”,”*”),可以设定“*”的对齐方式,第二个数字为正数表示靠右对齐,为负数表示靠左对齐,其余位置以空格补齐
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Class1
    {
        public static void Main()
        {
            int k = 0;
            int x = 7;
            int y;
//同样通过while循环控制行数
            while (k < 4)
            {
//使用Console.Write的格式控制,根据行数调整缩进,并输出每行的第一个“*”
                Console.Write(“{0,” + (k*2+1).ToString() + “}”, “*”);
//输出其余的“*”
                for (y = 0; y < x – 1; y++)
                    Console.Write(“*”);
                Console.Write(“/n”);
                k++;
                x -= 2;
            }
        }
    }
}
这两种方法,哪一种更快呢,来用计一下时吧
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Class1
    {
        public static void Main()
        {
            Stopwatch sw;
            int i, j, m, n;
            m = 0;
            n = 7;
            sw = Stopwatch.StartNew();
            while (m < 4)
            {
                for (j = 0; j < m * 2; j++)
                {
                    Console.Write(” “);
                }

                for (i = 0; i < n; i++)
                {
                    Console.Write(“*”);
                }
                Console.Write(“/n”);
                m++;
                n -= 2;
            }
            Console.WriteLine(“花费/t{0}”, sw.Elapsed);
            int k = 0;
            int x = 7;
            int y;
            sw = Stopwatch.StartNew();
            while (k < 4)
            {
                Console.Write(“{0,” + (k*2+1).ToString() + “}”, “*”);
                for (y = 0; y < x – 1; y++)
                    Console.Write(“*”);
                Console.Write(“/n”);
                k++;
                x -= 2;
            }
            Console.WriteLine(“花费/t{0}”, sw.Elapsed);

        }
    }
}
最终结果如下
*******
  *****
    ***
      *
花费    00:00:00.0104164
*******
  *****
    ***
      *
花费    00:00:00.0031654
可以看出,少用了一个循环,速度快了很多

~~~~~~~~~~~~~~~~~我是分割线~~~~~~~~~~~~~~~~~~~~~

以上代码,在vs.net 2005中验证通过

点赞