杨辉三角的规律:
1、第n行有n个数字.
2、每一行的开始和结尾数字都为1。(用二维数组表示就是a[i][0]=1; a[i][j]=1(当i==j时))
3、第n+1行的第i个数字等于第n行的i-1个数字加上第n行的i个数字。(用二维数组表示就是 a[i+1][j]=a[i][j-1]+a[i][j];)
方法一:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int [][] a = new int [n][n];
for(int i = 0;i < a.length;i++) {
for(int j = 0;j <= i;j++) {
if(j == 0 || j == i) {
a[i][j] = 1;
}
else {
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
方法二:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] a = new int[n][];
for(int i=0;i<a.length;i++) {
a[i] = new int[i + 1];
}
for(int i = 0;i < a.length;i++) {
for(int j = 0;j < a[i].length;j++) {
if(j == 0 || i == j) {
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[i].length;j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
方法三:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
int number = 1;
System.out.format("%" + (n - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}