我正在尝试编写可计算Pascal三角形的程序,我在查找一些示例,但发现了这个示例。但是我不太了解pascal方法是如何工作的。但是其他一切都有意义。
import java.util.Scanner;
public class Pascal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows to print: ");
int rows = scanner.nextInt();
System.out.println("Pascal Triangle:");
print(rows);
scanner.close();
}
public static void print(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(pascal(i, j) + " ");
}
System.out.println();
}
}
public static int pascal(int i, int j) {
if (j == 0 || j == i) {
return 1;
} else {
return pascal(i - 1, j - 1) + pascal(i - 1, j);
}
}
}
答案 0 :(得分:0)
请参阅评论以进行澄清:
public static void print(int n) {
for (int i = 0; i < n; i++) { //iterate over 0 - (n-1) rows
for (int j = 0; j <= i; j++) { //iterate over 0 - i columns, so 1 line
//will have 1 columns second line 2 columns..
System.out.print(pascal(i, j) + " "); //print column value and space
}
System.out.println();
}
}
//return the value of row i, col j
public static int pascal(int i, int j) {
if ((j == 0) || (j == i)) { //value of first or last column is 1
return 1;
} else {//value of other columns is the sum of two values of previous row
return pascal(i - 1, j - 1) + pascal(i - 1, j);
}
}