package com.xxxx.test;
import java.util.Scanner;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 杨辉三角:
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
* ……
* */
Scanner sc = new Scanner(System.in);
System.out.print("请输入行数:");
int row = sc.nextInt();
//定义两个数组分别表示当前行和最后一行
int[] now = new int[row]; //当前行
int[] last = new int[row]; //上一行
//循环i ,外层循环控制行数
for(int i = 0;i < row ;i++){
//内层循环控制列数
for(int j = 0;j <= i;j++){
//判断当前行是否是第一行或最后一行
//当前行是第一行或最后一行
if(j == 0 || j == i){
System.out.print("1\t");
//将当前行的值存储到数组中
now[j] = 1;
}else{
//计算非当前行或最后一行(上一行+当前行),上一行为last[j-1]
System.out.print(last[j-1] + now[j]+"\t");
//将当前行的值存储到数组中+
now[j] = last[j-1] + now[j];
}
}
System.out.println();
//迭代操作,将当前行的值赋值给上一行
for(int j = 0;j <now.length;j++){
last[j] = now[j];
}
}
}
}
项目结构:
运行结果: