交错数组 杨辉三角[交错数组的长度是用户动态输入的]
复制代码
- using System;
- using System.Linq;
- namespace test31
- {
- internal class Program
- {
- private static void Main(string[] args)
- {
- Console.Write("请输入行数:");
- var nline = Convert.ToInt32(Console.ReadLine());
- var a = new int[nline][]; //定义由nline个元素组成的数组
- for (var n = 0; n < nline; n++) //每个元素的初始化
- {
- a[n] = new int[n + 2];
- }
- a[0][0] = 1;
- for (var i = 1; i < a.Length; i++) //交错数组中值的赋予
- {
- for (var j = 0; j < a[i].Length; j++)
- {
- if (j == 0)
- {
- a[i][j] = 1;
- }
- else if (j == i + 1)
- {
- a[i][j] = 0;
- }
- else
- {
- a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
- }
- }
- }
- foreach (var b in a) //数组的打印
- {
- //为了实现杨辉三角的居中对齐
- var str = "";
- if (b.Count() <= a.Count()) //防止报错
- {
- str = str.PadLeft(a.Count() - b.Count() + 1, '\t');
- Console.Write(str);
- }
- foreach (var c in b)
- {
- if (c != 0)
- {
- Console.Write(" " + c + "\t\t");
- }
- }
- Console.WriteLine();
- }
- Console.ReadKey();
- }
- }
- }
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |