楊輝三角

       楊輝三角形,又稱賈憲三角形,帕斯卡三角形,是二項式係數在三角形中的一種幾何排列。

       每個數字等於上一行的左右兩個數字之和。可用此性質寫出整個楊輝三角。

public void yanghui(int value)
        {
            if (value < 3)
            {
                Console.WriteLine("請重新輸入數組大於3的值!");
            }
            else
            {
                int[,] arry = new int[value, value];

                Console.WriteLine("數組爲:");

                for (int i = 0; i < value; i++)
                {

                    string str = "";
                    str = str.PadLeft(value - i);
                    Console.Write(str);

                    for (int j = 0; j <= i; j++)
                    {
                        if (i == j || j == 0)
                        {
                            arry[i, j] = 1;
                        }
                        else
                        {
                            arry[i, j] = arry[i - 1, j - 1] + arry[i - 1, j];
                        }
                        Console.Write(arry[i, j] + " ");
                    }
                    Console.WriteLine();
                }
            }
        }

        static void Main(string[] args)
        {
            Program p = new Program();

            Console.WriteLine("請輸入數組值:");

            string str_name = Console.ReadLine();

            int value = Convert.ToInt16(str_name);

            p.yanghui(value);

            Console.ReadKey();
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章