import static java.lang.System.out;
/**
* ClassName:yangHuiTest
*
* @author: swimer
* @description: 杨辉三角 输出一个10行的杨辉三角
* @date: 20/01/27下午 8:16
* version:1.0
* @since: jdk 1.8
*/
public class YangHuiTest {
public static void main(String[] args) {
//定义一个二维数组存放10行的杨辉三角
int[][] yangHui = new int[10][];
for (int i = 0; i < yangHui.length; i++) {
yangHui[i] = new int[i + 1];
}
// System.out.println(yangHui);
// 给杨辉三角赋值
// 每行首尾均为1 非首尾则符合 yangHui[i][j]=yangHui[i-1][j]+yangHui[i-1][j-1]
for (int i = 0; i < yangHui.length; i++) {
for (int j = 0; j < yangHui[i].length; j++) {
yangHui[i][0] = yangHui[j][j] = 1;
}
//非首尾行赋值
for(int j=1;j<yangHui[i].length-1;j++){
yangHui[i][j]=yangHui[i-1][j]+yangHui[i-1][j-1];
}
}
//遍历打印数组
for (int[] ints : yangHui) {
for (int j = 0; j < ints.length; j++) {
out.print(ints[j] + "\t");
}
//打印完内层一次再换行
out.println();
}
}
}
杨辉三角(数组运用)
最新推荐文章于 2024-08-19 23:56:23 发布