java编写杨辉三角
展开全部
import java.util.Scanner;
public class PascalTriangle {
public static void main(String[] args) {
System.out.print("Please input a digit for pascal triangle: ");
Scanner scanner = new Scanner(System.in);
final int num = scanner.nextInt();
int[][] ary = getPascalTriangle(num);
for(int[] item: ary){
for(int value: item){
System.out.print((value > 0? value: "") + " ");
}
System.out.println();
}
}
private static int[][] getPascalTriangle(final int num) {
int[][] ary = new int[num][num];
for(int i = 0; i < ary.length; i++){
ary[i][0] = 1;
ary[i][i] = 1;
}
for(int i = 1; i < ary.length; i++){
for(int j = 1; j <= i; j++){
ary[i][j] = ary[i-1][j-1] + ary[i-1][j];
}
}
return ary;
}
}
-----------------
Please input a digit for pascal triangle: 7
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
public class PascalTriangle {
public static void main(String[] args) {
System.out.print("Please input a digit for pascal triangle: ");
Scanner scanner = new Scanner(System.in);
final int num = scanner.nextInt();
int[][] ary = getPascalTriangle(num);
for(int[] item: ary){
for(int value: item){
System.out.print((value > 0? value: "") + " ");
}
System.out.println();
}
}
private static int[][] getPascalTriangle(final int num) {
int[][] ary = new int[num][num];
for(int i = 0; i < ary.length; i++){
ary[i][0] = 1;
ary[i][i] = 1;
}
for(int i = 1; i < ary.length; i++){
for(int j = 1; j <= i; j++){
ary[i][j] = ary[i-1][j-1] + ary[i-1][j];
}
}
return ary;
}
}
-----------------
Please input a digit for pascal triangle: 7
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
参考资料: http://zhidao.baidu.com/question/248766934.html
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询