0
点赞
收藏
分享

微信扫一扫

打印杨辉三角

笙烛 2022-02-07 阅读 74
java

代码略显粗糙
有可优化的地方可以留言指教,不胜感激

import java.util.Scanner;

public class array{
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		//设置杨辉三角的层数
		System.out.println("enter the floors of Yanghui triangle");
		int floor = input.nextInt();

		//设置杨辉三角
		int yanghui[][] = new int[floor][];
		for (int i = 0; i < floor ;i++) {
			yanghui[i] = new int[i+1];
			for (int j = 0; j < yanghui[i].length ; j++) {
					if(j==0 || j == yanghui[i].length -1){
						//边缘为1
						yanghui[i][j] = 1;
					}else{
						//为左上与正上的数字相加
						yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
					}	
				}	
			}

		//打印杨辉三角
		for (int i = 0;i < yanghui.length ;i++) {
			for (int j =0;j < yanghui[i].length ;j++ ) {
				System.out.print(yanghui[i][j] + " ");
			}
			System.out.println();
		}
	}
}
举报

相关推荐

0 条评论