在C#中用交错数组写出杨辉三角形。
Console.WriteLine("请输入你要打印的行数:");
int k = int.Parse(Console.ReadLine());//指定杨辉三角形的长度
int[][] scores = new int[k][];//二维数组,交错数组
for (int i = 0; i < scores.Length; i++)
{
scores[i] = new int[i + 1];//遍历,赋值增量
}
for (int i = 0; i < scores.Length; i++)
{
scores[i][0] = 1;//把第1列的元素都赋1
scores[i][i] = 1;//把每1列最右边的元素都赋1
for (int j = 1; j < scores[i].Length - 1; j++)
{
scores[i][j] = scores[i - 1][j - 1] + scores[i - 1][j];//其余元素的值由杨辉公式计算
}
}
for (int i = 0; i < scores.Length; i++)
{
for (int j = 0; j < scores[i].Length; j++)
{
Console.Write(" "+scores[i][j]);// 遍历数组输出杨辉三角形
}
Console.WriteLine();
}
输出的结果为
![](https://i-blog.csdnimg.cn/blog_migrate/8de6172734d01c09c561934ddaf5c5f0.png)