java打印杨辉三角

来源:互联网 发布:萧山网络问政关注 编辑:程序博客网 时间:2024/05/17 03:13

第一种实现:

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(); //每层换行        }}}

结果:

请输入要打印多少行:101 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