/*题目:杨辉三角形
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* */
* //提醒:当你输入的行数太大了,它的值就会超出int的范围,就会溢出
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//输入要输出的杨辉三角行数
System.out.print("输入要输出的杨辉三角行数:");
int n = scanner.nextInt();
YangHuiTriangle(n);
}
public static void YangHuiTriangle(int n){
int[][] arr = new int[n][n];
arr[0][0] = 1;
arr[1][0] = 1; arr[1][1] = 1;
for (int i = 2; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i){
arr[i][j] = 1;
}else {
arr[i][j] = arr[i-1][j-1]+arr[i-1][j];
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 10-i; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%3d ",arr[i][j]);
}
System.out.println();
}
Java杨辉三角
最新推荐文章于 2024-11-04 22:26:34 发布