我正在尝试创建并正确格式化Pascal的三角形,其中用户输入值“n”表示将输出的行数。这里的问题是获得超过13行的正确格式。我认为问题在于%4d,因为超过第13行的数字往往需要4个以上的空格。我只是不知道如何为(基本上)无限的n值实现类似的东西(我知道双变量的局限性,但我希望你理解我的意思)。另外,我更喜欢没有实现数组使用的解决方案。
double n;
for (int i = 0; i < n; i++){
int number = 1;
System.out.printf("%" + (n - i) * 2 + "s", "");
for (int j = 0; j <= i; j++){
System.out.printf("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
答案 0 :(得分:0)
这是使用矩阵的可能解决方案......
import java.util.Scanner;
public class PascalTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Type N: ");
pascalTriangle(scanner.nextInt());
scanner.close();
}
public static void pascalTriangle(final int N) {
int[][] triangle = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0)
triangle[i][0] = 1;
else
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
System.out.print(triangle[i][j] + "\t");
}
System.out.println();
}
}
}
输出:
Type N: 13
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
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
答案 1 :(得分:0)
这是使用数学公式代替数组的更好解决方案:
import java.util.Scanner;
public class PascalTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Type N: ");
pascalTriangle(scanner.nextInt());
scanner.close();
}
public static void pascalTriangle(final int N) {
int row, num;
for (int i = 0; i < N; i++) {
num = 1;
row = i + 1;
for (int col = 0; col <= i; col++) {
if (col > 0)
num = num * (row - col) / col;
System.out.print(num + "\t");
}
System.out.println();
}
}
}
输出:
Type N: 13
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
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1