這篇文章將為大家詳細講解有關C#實現楊輝三角的案例,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
C# 中楊輝三角的實現
問題描述:創建一個程序來求三角形。該程序提示用戶輸入數據,然后顯示出楊輝三角的規律。
// 輸入描述:楊輝三角長,代表數值
// 程序輸出:楊輝三角
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int length = 0;//楊輝三角形的長度 Console.Write("輸入楊輝三角長度:"); length = Convert.ToInt32(Console.ReadLine());//指定楊輝三角形的長度 int[][] a = new int[length][];//二維數組 for (int i = 0; i < a.Length; i++) a[i] = new int[i + 1];//遍歷,賦值增量 for (int j = 0; j < a.Length; j++) { a[j][0] = 1; //把第1列的元素都賦1 a[j][j] = 1; //把每1列最右邊的元素都賦1 for (int m = 1; m < a[j].Length - 1; m++) a[j][m] = a[j - 1][m - 1] + a[j - 1][m];//其余元素的值由楊輝公式計算 } for (int i = 0; i < a.Length; i++) //遍歷數組輸出楊輝三角形 { for (int j = 0; j < a[i].Length; j++) Console.Write("{0}\t", a[i][j]); Console.Write("\n"); } Console.Read(); } } }
關于C#實現楊輝三角的案例就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。