打印杨辉三角 (10行)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
自己输入行数
import java.util.Scanner;
public class Demo{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入杨辉三角的行高(小于25):");
int line = sc.nextInt();
int[][] arr = new int[line][line];
//System.out.println(arr.length);
//外层循环控制行数
for (int i = 0; i < arr.length; i++) {
//内层循环控制列数
for (int j = 0; j < i + 1; j++) {
if (j == 0 || j ==i ) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
}
}
//System.out.println(arr[0][0]);
/*for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}*/
//外层循环控制行数
for (int i = 0; i < line; i++) {
//先输出空格
for (int j = 0; j < line - 1 - i; j++){
System.out.print(" ");
}
//再输入数据
for (int k = 0; k < i + 1; k++) {
System.out.printf("%-8d",arr[i][k]);
}
System.out.println();
}
}
}
不用数组存储,直接打印
public class Yh {
public static void main(String[] args) {
int rows=10;
for( int i=0;i<rows;i++){
int number=1;
System.out.printf("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++){
System.out.printf("%4d",number);
number=number*(i-j)/(j+1);
}
System.out.println();
}
}
}