C杨辉三角
以前大一刚开始学的时候还觉得打印杨辉三角有点难度。
现在大三了,C#居然又要我们打印一次。
哎,发现好多语言的书本教学套路都是差不多的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace c4._6
{
class Program
{
const int MAX= 10;
static void Main(string[] args)
{
Program.showTriangle(MAX);
Console.ReadKey();
}
public static void showTriangle(int LINE)
{
int [,]triangle=new int[LINE,LINE];
for (int i = 0; i < LINE; i++)//先令每一个元素都为1
for (int j = 0; j < LINE; j++)
triangle[i, j] = 1;
for (int i = 0; i < LINE; i++)//构造杨辉三角
for (int j = 1; j < i; j++)//每排第一个和最后一个不变
triangle[i, j] = triangle[i - 1, j] + triangle[i - 1, j - 1];
//其他的为上一层头顶和左边一个之和
for (int i = 0; i < LINE; i++)
{
for (int j = 0; j <= i; j++)
Console.Write(" {0,4}", triangle\[i, j\]);
Console.WriteLine();
}
}
}
}
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/c杨辉三角/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!