0
這裏是輸出帕斯卡三角形的一些代碼,它顯示了三角形的所有線條。例如,如果用戶輸入是5,那麼它將輸出如下:帕斯卡爾三角形 - 只打印第n行
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中的打印語句之前已經嘗試過各種if語句,但似乎無法找到按預期工作的語句。 –