杭电2032 杨辉三角 Java

 源代码:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4 
 5     public static void main(String[] args) {
 6         Scanner scanner = new Scanner(System.in);  // receive data
 7         while (scanner.hasNext()) {
 8             int num = scanner.nextInt();
 9             pascalTriangle(num);  // call function
10         }
11         scanner.close();
12     }
13 
14     public static void pascalTriangle(int num) {    // create pascalTriangle function
15         int[][] array = new int[num][num];
16         for (int i = 0; i < array.length; i++) {  // data storage
17             for (int j = 0; j <= i; j++) {
18                 if (i == j || j == 0) {
19                     array[i][j] = 1;
20                 } else if (i > 0) {
21                     array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
22                 }
23             }
24         }
25         for (int i = 0; i < num; i++) {  // print
26             for (int j = 0; j <= i; j++) {
27                 if (i == j) {
28                     System.out.print(array[i][j]);
29                 } else {
30                     System.out.print(array[i][j] + " ");
31                 }
32             }
33             System.out.println();
34         }
35         System.out.println();
36     }
37 }

 测试结果:

 

猜你喜欢

转载自www.cnblogs.com/zhangKaiXi/p/9439742.html
今日推荐