帕斯卡的三角形二维数组 - 格式化打印输出 [英] Pascal's triangle 2d array - formatting printed output
问题描述
我有一个小任务,我必须使用二维数组来生成帕斯卡三角形.这是我的代码,它有效.如果我像这样显示三角形,还有一个额外的信用机会:
I have a small assignment where I have to use a 2d array to produce Pascal's triangle. Here is my code, and it works. There is an extra credit opportunity if I display the triangle like so:
但是,我的间距不是那样格式的.它只是显示所有排列在左侧的数字.这很难描述,但如果你运行它,你就会明白我的意思.
However, my spacing is not formatted like that. it simply displays the numbers all lined up on the left. its hard to describe but if you run it you will see what I mean.
这是我的代码:
public class Pascal {
public static final int ROW = 16;
public static void main(String[] args) {
int[][] pascal = new int[ROW + 1][];
pascal[1] = new int[1 + 2];
pascal[1][1] = 1;
for (int i = 2; i <= ROW; i++) {
pascal[i] = new int[i + 2];
for (int j = 1; j < pascal[i].length - 1; j++) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
for (int i = 1; i <= ROW; i++) {
for (int j = 1; j < pascal[i].length - 1; j++) {
System.out.print(pascal[i][j] + " ");
}
System.out.println();
}
}
}
如果有人能帮我弄清楚如何在我的程序中添加正确的间距以产生图片中所需的输出,那就太好了.我知道我需要在某处放置一个 System.out.print(" ")
.我只是不知道在哪里.
If someone could help me figure out how to add the correct spacing to my program to produce the output desired in the picture, that would be great. I know I need to put a System.out.print(" ")
somewhere. I just dont know where.
推荐答案
这里我修改了你的代码,由于我的控制台窗口的限制,它可以很好地打印到 13 行大小:
Here I had modified your code, it prints wonderfully for ROW size till 13, because of the limitation of my console window:
import java.util.*;
public class Pascal {
public static final int ROW = 12;
private static int max = 0;
public static void main(String[] args) {
int[][] pascal = new int[ROW + 1][];
pascal[1] = new int[1 + 2];
pascal[1][1] = 1;
for (int i = 2; i <= ROW; i++) {
pascal[i] = new int[i + 2];
for (int j = 1; j < pascal[i].length - 1; j++) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
String str = Integer.toString(pascal[i][j]);
int len = str.length();
if (len > max)
max = len;
}
}
for (int i = 1; i <= ROW; i++) {
for (int k = ROW; k > i; k--)
System.out.format("%-" + max + "s", " ");
for (int j = 1; j < pascal[i].length - 1; j++)
System.out.format("%-" + (max + max) + "s", pascal[i][j]);
System.out.println();
}
}
}
输出:
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
这篇关于帕斯卡的三角形二维数组 - 格式化打印输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!