【程序33】
题目:打印出杨辉三角形(要求打印出10行如下图)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
…………
package com.share.test_31_40;
/**
* @author Administrator 核心在于打印中间的那几个规律 貌似可以用递归来做
* 一个二维数组,二维的数组中一维的长度递增,边缘的值为1,其他的值都是通过数组中上一层的数来确定的
*/
public class Test33 {
public static void main(String[] args) {
test1();
}
public static void test() {
int max = 10;
for (int i = 0; i < max; i++) {
for (int j = 0; j < max - i; j++) {
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++) {
if ((j + 1) % 2 == 0) {
System.out.print(" ");
continue;
}
if (j == 0 || j == 2 * i) {
System.out.print(" 1");
} else {
System.out.print(" " + (i));
}
}
System.out.println();
}
}
/**
* 先生成数组,然后再思考打印的排版
*/
public static void test1() {
// 动态生成一个二维数组
int[][] a = new int[10][];
for (int i = 0; i < a.length; i++) {
a[i] = new int[i + 1];
for (int j = 0; j < a[i].length; j++) {
if (j == 0 || j == (a[i].length - 1)) {
a[i][j] = 1;
} else {
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i; j++) {
System.out.print(" ");
}
for (int j = 0; j < a[i].length; j++) {
if(j!=0){
System.out.print(" ");
}
if(a[i][j]<10){
System.out.print(" ");
}
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
网友评论