1. 程式人生 > >實驗四:采用一維數組輸出等腰三角形的楊輝三角。

實驗四:采用一維數組輸出等腰三角形的楊輝三角。

代碼 system 源代碼 public 運行 pack 技術分享 system.in oid

技術分享圖片

源代碼:

package 楊輝三角;

import java.util.Scanner;

public class YHSJ {
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
System.out.print("請輸入楊輝三角的層數:");
int i,j,n,k;
n=cs.nextInt();
k=n;
int yhsj[]=new int[n];
yhsj[0]=yhsj[1]=yhsj[2]=1;
System.out.println(" "+yhsj[0]);

for(i=0;i<2;i++)
System.out.print(" "+yhsj[i]);
System.out.println();
for(i=3;i<=n;i++) {
yhsj[i-1]=1;
for(j=i-2;j>0;j--)
yhsj[j]=yhsj[j]+yhsj[j-1];
yhsj[0]=1;

for(j=0;j<i;j++)
System.out.print(" "+yhsj[j]);
System.out.println();
}
}
}

運行結果:

技術分享圖片

總結心得:因為楊輝三角得先知道前兩行的值才能算出後面的值,因此只要理解了楊輝三角的規律,就能利用數組弄出來。

實驗四:采用一維數組輸出等腰三角形的楊輝三角。