第6關:輸出楊輝三角


任務描述

題目描述:還記得中學時候學過的楊輝三角嗎?具體的定義這里不再描述,你可以參考以下的圖形:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

編寫程序,輸出楊輝三角的前n行,要求從鍵盤輸入n的值。

輸入

從鍵盤輸入n的值。

輸出

打印出楊輝三角圖形的前n行。格式見題目描述部分。每個整數后面接一個空格來分隔開整數

編程要求

根據提示,在右側編輯器補充代碼。

編程提示

假設數組名為a,則數組元素的輸出格式建議采用如下格式:

Console.Write("{0} ",a[i,j]);

測試說明

平台會對你編寫的代碼進行測試:

測試輸入:

4

預期輸出:

1

1 1

1 2 1

1 3 3 1

測試輸入:

6

預期輸出:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1


開始你的任務吧,祝你成功!

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ch706
{
    class Program
    {
        static void Main(string[] args)
        {
			/******begin*******/
			int n = Convert.ToInt32(Console.ReadLine());
            int[,] a = new int[n, n];
            
            for (int i = 0; i < a.GetLength(0); ++i)
            {
                for (int j = 0; j <= i; ++j)
                {
                    if(j == 0 || i == j)
                    {
                        a[i, j] = 1;
                    }
                    else
                    {
                        a[i,j] = a[i - 1,j] + a[i-1,j-1];
                    }
                    Console.Write(a[i,j].ToString() + " ");
                }
                Console.WriteLine();
            }

			
			
			/*******end********/

        }
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM