这里是一些输出帕斯卡三角形的代码,它显示了三角形的所有线。例如,如果用户输入为5,则输出如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
不过,我只想让它输出最后一行。所以对于 5,只有 1 4 6 4 1。我很难完成这个,尽管我知道这很容易。如有任何帮助,我们将不胜感激。
import java.util.Scanner;
public class PascalsTriangle {
public static void computeRow(int n) {
int counter;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(pascalValue(i, j) + " ");
}
System.out.println();
}
}
public static int pascalValue(int i, int j) {
if (j == 0) {
return 1;
} else if (j == i) {
return 1;
} else {
return pascalValue(i - 1, j - 1) + pascalValue(i - 1, j);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Which line number of Pascal's Triangle? ");
int row = scanner.nextInt();
System.out.print("Line " +row+" of Pascal's Triangle:\n");
computeRow(row);
}
}
最佳答案
更改您的 computeRow()
方法以包含对您要打印的三角形的特定线的检查。在您的情况下,您只想打印最后一行,这将在外部 for
循环的 last 迭代期间发生:
public static void computeRow(int n) {
int counter;
for (int i = 0; i < n; i++) {
// only output the line if it be the last one
if (i == n-1) {
for (int j = 0; j <= i; j++) {
System.out.print(pascalValue(i, j) + " ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
computeRow(5);
}
输出:
Line 5 of Pascal's Triangle:
1 4 6 4 1
关于java - 帕斯卡三角形 - 仅打印第 'n' 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865077/