java打印杨辉三角

第一种实现:

package com.jn.test;

import java.util.Scanner;

public class Triangle {

	public static void main(String[] args) {
	        Scanner sc = new Scanner(System.in);
	        System.out.println("请输入要打印多少行:");
	        int lines = sc.nextInt();
	        int[] arr = new int[lines + 1];
	        int previous = 1;
	        for (int i = 1; i <= lines; i ++){
	            for (int j = 1; j <= i; j++){
	                int current = arr[j];
	         /* 新位置的元素 = 该位置原来的元素 + 该位置的前一个位置的元素 */
	                arr[j] = previous + current;  
	                previous = current;
	                System.out.print(arr[j] + " \t");
	            }
	            System.out.println(); //每层换行
	        }
	}
}

结果:

请输入要打印多少行:
10
1 	
1 	1 	
1 	2 	1 	
1 	3 	3 	1 	
1 	4 	6 	4 	1 	
1 	5 	10 	10 	5 	1 	
1 	6 	15 	20 	15 	6 	1 	
1 	7 	21 	35 	35 	21 	7 	1 	
1 	8 	28 	56 	70 	56 	28 	8 	1 	
1 	9 	36 	84 	126 	126 	84 	36 	9 	1 

第二种实现:

package com.jn.test;

import java.util.Scanner;

public class Triangle2 {

	public static void main(String[] args) {
	        Scanner sc = new Scanner(System.in);
	        System.out.println("请输入要打印多少行:");
	        int x = sc.nextInt();//输入几层是几层  
	        int num[][] = new int[x][x];//这个数组有几层  
	        for(int m=0;m<x;m++)//主要是对数组进行赋值  
	        {  
	            for(int n=0;n<=m;n++)//每一层的个数都是小于等于层数的,m代表层数,n代表着第几个数  
	            {  
	                if(n==0||m==n)//每一层的开头都是1,m==n的时候也是1,必须要这个,凡事都得有个开头   
	                {  
	                    num[m][n]=1;  
	                }  
	                else  
	                    num[m][n]=num[m-1][n-1]+num[m-1][n];//这个就是递推的方法了,例如3=1+2,3的坐标就是3[3,1]=1[2,0]+2[2,1];  
	            }  
	        }  
	        for(int i=0;i<x;i++)//主要是输出数组  
	        {  
	            for(int l=i;l<x;l++)//这个主要是打空格,好看一点,去掉就是直角三角形了  
	            {  
	                System.out.print(" ");  
	            }  
	            for(int j=x-i;j<=x;j++)//这个就是打印数组了,每层循环几次就几个  
	            {  
	                System.out.print(num[i][x-j]+" ");//不懂的可以把x替换成10,更加清楚点  
	            }  
	            System.out.println();//每层换行  
	        }  
	}
}

结果:

请输入要打印多少行:
10
          1 
         1 1 
        1 2 1 
       1 3 3 1 
      1 4 6 4 1 
     1 5 10 10 5 1 
    1 6 15 20 15 6 1 
   1 7 21 35 35 21 7 1 
  1 8 28 56 70 56 28 8 1 
 1 9 36 84 126 126 84 36 9 1 


转载于:https://www.cnblogs.com/mlan/p/11060357.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值