码迷,mamicode.com
首页 > 其他好文 > 详细

打印杨辉三角形

时间:2014-12-14 17:18:48      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:循环嵌套   杨辉三角   二维数组   java   打印   

import java.util.Scanner;


public class Yanghui {

	public static void main(String[] args) {
		System.out.print("请输入你要打印的杨辉三角的层数:");
		Scanner sc = new Scanner(System.in);
		sc.close();
		int height =sc.nextInt();	//杨辉三角的高度(层数)

		int row = 2*height-1;	
	    int[ ][ ] yh = new int[height][row];
	    int j=0;
	    
	    int temp_row=row-1;
		for(int i=height-1;i>=0;i--)
		{
			yh[i][j++]=1;						//将左面一斜排的值全设为1
			
			yh[i][temp_row--]=1;			//将右面一斜排的值全设为1
		}
		
		
		for(int i=2;i<height;i++)
		{
			for(j=height-1-i+2;j<row-2;j+=2)		//对某一行而言,得到除首尾为1之外的其他值
			{
					yh[i][j]=yh[i-1][j-1]+yh[i-1][j+1];
			}
			
		}
		
		
		for(int m=0;m<height;m++)
		{
			for(int n=0;n<row;n++)
			{
				if(yh[m][n]==0)
					System.out.print(" ");
				else
					System.out.print(yh[m][n]);
			}
			System.out.println();
		}

	}

}
bubuko.com,布布扣

打印杨辉三角形

标签:循环嵌套   杨辉三角   二维数组   java   打印   

原文地址:http://blog.csdn.net/huolang_vip/article/details/41925779

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!