java 杨辉三角
java 楊輝三角,請編寫一個程序,按題目要求輸出楊輝三角中第 n 行第 m 個數字。
// 楊輝三角值遞歸計算
public static long numYH(int x, int y) {
if (y == 1 || y == x) {
// 第一列和 x=y 的列都為1
return 1;
} else {
// 中間部分的值遞歸計算
return numYH(x - 1, y - 1) + numYH(x - 1, y);
}
}
public static void main(String[] args) {
System.out.println("輸出楊輝三角中第 n 行第 m 個數字?");
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入楊輝三角行數: ");
//楊輝三角行數
int rowsYH = scanner.nextInt();
System.out.print("請輸入楊輝三角列數: ");
//楊輝三角列數
int colsYH = scanner.nextInt();
scanner.nextLine();
System.out.println("======================楊輝三角:start");
System.out.println("楊輝三角第" + rowsYH + "行,第" + colsYH + "列的值是:" + numYH(rowsYH, colsYH));
System.out.println("==============不信你看看下面:");
for (int i = 1; i <= rowsYH; i++) {
// 左邊空格區,把直角三角形擠壓成等腰三角形
for (int j = 1; j <= rowsYH - i; j++) {
//每列4位空格
System.out.format("%4s", "");
}
// 數字區
for (int j = 1; j <= i; j++) {
//控制每列數值8位長度
System.out.format("%8d", numYH(i, j));
}
System.out.println();
}
System.out.println("======================楊輝三角:end");
}
結果:
輸出楊輝三角中第 n 行第 m 個數字?
請輸入楊輝三角行數: 7
請輸入楊輝三角列數: 5
======================楊輝三角:start
楊輝三角第7行,第5列的值是:15
==============不信你看看下面:
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
======================楊輝三角:end
總結
- 上一篇: 【两】的拼音、繁体字、笔画
- 下一篇: 【丝】的拼音、繁体字、笔画