XX面试题

是一题笔试题,也没有什么难点,当时写这道题的时候太唐突了,
今天回来再机子上重新完善完善了

题面:请打印以下图形

   *
  ***
 *****
*******
 *****
  ***
   *
 
class Program
    {
        
private const string flag = "*";
        
private const char snull = ' ';
        
private const int length = 7;

        
/// <summary>
        
/// 主函数
        
/// </summary>
        
/// <param name="args"></param>
        static void Main(string[] args)
        {
            
//----------正向打印
            for (int i = 0; i <= length; i++)
                
if (i % 2 != 0)
                    PrintFlag(i);

            
//-----------反向打印
            for (int i = length - 2; i > 0; i--)
                
if (i % 2 != 0)
                    PrintFlag(i);

            Console.Read();
        }

        
/// <summary>
        
/// 打印标记
        
/// </summary>
        
/// <param name="currentIndex">当前索引</param>
        static void PrintFlag(int currentIndex)
        {
            
string t = string.Empty, s = string.Empty;
            
for (int i = 0; i < currentIndex; i++)
            {
                t 
+= flag;
            }
            s 
= GetLocation(currentIndex, t);//获取字符串及所在位置
            Console.WriteLine(s);
        }

        
/// <summary>
        
/// 获取“标记”位置
        
/// </summary>
        
/// <param name="currentIndex">当前索引</param>
        
/// <param name="flag">标记</param>
        
/// <returns></returns>
        static string GetLocation(int currentIndex, string flag)
        {
            
int totalcount = length;
            
if (currentIndex == totalcount)
                
return flag;

            
int startlocation = (totalcount - currentIndex) / 2;//中间位置
            string temp = flag.PadLeft(startlocation + currentIndex, snull);//前置空白
            temp = temp.PadRight(totalcount, snull);//后置空白
            return temp;
        }
    }

 


 

 

 




如果有更好的方法,希望大家多补充哈

posted on 2009-10-09 17:03  RedFox(低调)  阅读(675)  评论(15编辑  收藏  举报

导航