用c#语言控制台程序求输入一个i值,就能输出一个等腰三角形和一个菱形,i分别为三角形的高和菱形的竖

2024-12-16 17:26:44
推荐回答(1个)
回答1:

static void Main(string[] args)    //三角形
        {
            int height=0;
            Console.WriteLine("请输入三角形的高");
            bool flag = true;
            do
            {
                try
                {
                    height = int.Parse(Console.ReadLine());
                    flag = false;
                }
                catch (Exception)
                {

                    Console.WriteLine("请重新输入");
                    
                }
            } while (flag);
            
            for (int i = 1; i <= height; i++)
            {
                for (int j = i; j < height; j++)
                {
                    Console.Write(" ");
                }
                for (int j = 1; j <= 2*i-1; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }

 

static void Main(string[] args)//菱形
        {
            int height = 0;
            Console.WriteLine("请输入菱形的行数(奇数)");
            bool flag = true;
            do
            {
                try
                {
                    height = int.Parse(Console.ReadLine());
                    if (height%2!=0)
                    {
                       flag = false;
                    }
                    else
                    {
                        Console.WriteLine("请输入一个奇数");
                    }
                    
                }
                catch (Exception)
                {

                    Console.WriteLine("请输入正确的数字");

                }
            } while (flag);
            int top = height / 2 + 1;
            int dow = height - top;
            for (int i = 1; i <= top; i++)
            {
                for (int j = i; j < top; j++)
                {
                    Console.Write(" ");
                }
                for (int j = 1; j <= 2 * i - 1; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            for (int i = dow; i >=0; i--)
            {
                for (int j = i; j < top; j++)
                {
                    Console.Write(" ");
                }
                for (int j = 1; j <= 2 * i - 1; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }