小时候学的了,现在都忘记了。
using System; /*杨辉三角 该数字序列的规律为,数组中第一列的数字值都是1,后续每个元素的值等于该行上一行对应元素和上一行对应前一个元素的值之和。例如第五行第二列的数字4的值,等于上一行对应元素3和3前面元素1的和。 实现思路:杨辉三角第几行有几个数字,使用行号控制循环次数,内部的数值第一行赋值为1,其它的数值依据规则计算。假设需要计算的数组元素下标为(row,col),则上一个元素的下标为(row – 1,col),前一个元素的下标是(row – 1,col – 1)。 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 */ namespace windysho { public class yanghui { public static void Main() { int[,] arr = new int[11,11]; //循环赋值 for(int row = 0;row < arr.GetLength(0);row++) { for(int col = 0;col <= row;col++) { if(col == 0) { //第一列 arr[row , col] = 1; } else { arr[row , col] = arr[row - 1 , col] + arr[row - 1 , col - 1]; } } } //输出数组的值 for(int row = 0;row < arr.GetLength(0);row++) { for(int col = 0;col <11 ;col++) { Console.Write(arr[row , col].ToString().PadRight(5)); Console.Write(" "); } Console.WriteLine(""); } } } }