输入n行的杨辉三角java,杨辉三角 Java代码 可以根据输入 输出相应行数的杨辉三角...
/**
* @see 打印出楊輝三角形(這是用的多維數(shù)組的形式,也可以根據(jù)公式計(jì)算),輸出樣式已經(jīng)進(jìn)行了調(diào)整
*/
class YangHuiSanJiao {
public static void main(String[] args) {
System.out.println("請(qǐng)輸入正整數(shù)");
Scanner s = new Scanner(System.in);
String input = s.next();
int number;
try {
number = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("您輸入的不是整數(shù)");
return ;
}
if (number <= 0) {
System.out.println("您輸入的不是正整數(shù)");
return ;
}
int length = number * 2 -1; //第二維數(shù)組的長(zhǎng)度
long[][] array = new long[number][length]; //已經(jīng)默認(rèn)賦值為0
//第一行處理
array[0][length / 2] = 1;
//i為當(dāng)前打印的行數(shù),在數(shù)組中的表示為i - 1
for (int i = 2; i <= array.length; i++) {
for (int j = 0; j < length; j++) {
if (j - 1 < 0) { //第一個(gè)位置
array[i - 1][j] = array[i - 2][j + 1];
continue ;
}
if (j + 1 >= length) { //最后一個(gè)位置
array[i - 1][j] = array[i - 2][j - 1];
continue ;
}
if (array[i - 2][j - 1] > 0 || array[i - 2][j + 1] > 0) { //有數(shù)字出現(xiàn)的位置
array[i - 1][j] = array[i - 2][j - 1] + array[i - 2][j + 1];
continue ;
}
}
}
//獲取數(shù)組中的最大值
總結(jié)
以上是生活随笔為你收集整理的输入n行的杨辉三角java,杨辉三角 Java代码 可以根据输入 输出相应行数的杨辉三角...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中国各省省名的由来
- 下一篇: Java socket编程 CPU占用率