题目:杨辉三角的实现打印(可以控制行数)
import java.util.Scanner;
public class YangHui {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入杨辉三角的行数:");
int row = sc.nextInt();
int[][] arr = new int[row][2*row+1];
//杨辉三角的第一行第一个元素
arr[0][row] = 1;
//遍历杨辉三角为里面的元素赋值
for(int i=1; i<row; i++){
for(int j=row-i; j<=row+i; j++){
arr[i][j] = arr[i-1][j-1]+arr[i-1][j+1];
}
}
//遍历杨辉三角里面的元素,并且打印出来
for(int i=0; i<row; i++){
for(int j=0; j<2*row+1; j++){
if(arr[i][j] == 0){
System.out.print(" ");
}else{
if(arr[i][j] < 10){
System.out.print(" "+arr[i][j]);
}else if(arr[i][j] < 100){
System.out.print(" "+arr[i][j]);
}else if(arr[i][j] < 1000){
System.out.print(" "+arr[i][j]);
}else{
System.out.print(arr[i][j]);
}
}
}
System.out.println();
}
}
} |
|