C#輸出楊輝三角形
阿新 • • 發佈:2017-08-25
效果 oid 輸出 代碼 console nbsp class div 直接
話不多說直接上代碼:
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 k = 0; k < length -i;k++) Console.Write(" "); for (int j = 0; j < a[i].Length; j++) Console.Write("{0} ", a[i][j]); Console.Write("\n"); } Console.Read(); } }
運行效果如下
C#輸出楊輝三角形