杨辉三角java实现

import java.util.Scanner;
/** * 类的文档注释 * @author Loweir * @version 1.0 * @since 1.8 * 按用户输入的阶数输出对应的杨辉三角 */
public class YangHui {
    public static void main(String[] args) {
        YangHui yHui = new YangHui();
        Scanner input = new Scanner(System.in);
        System.out.println("杨辉三角");
        System.out.print("输入杨辉三角的阶数:");
        int number = input.nextInt();
        yHui.yangHuiAngle(number);
        yHui.yangHuiAngle1(number);
        input.close();
    }
    //使用组合方式计算杨辉三角
    void yangHuiAngle(int number){
        double result,temp1=1,temp3 = 1;
        for(int i = 0;i<number;++i){
            for(int countSpace = 0;countSpace<(number-i)/2;++countSpace)
                System.out.print(" ");
            if((i+1)%2 == number%2){
                System.out.print(" ");
            }
            System.out.print("1 ");
            for(int count = i,temp2 = 1;count >= 1;--count,++temp2){
                temp1 *= count;
                temp3 *= temp2;
                result = temp1 / temp3;
                System.out.printf("%-8.0f",result);
            }
            System.out.println();
        }       
    }
    //使用两肩之和的方式计算杨辉三角
    void yangHuiAngle1(int number){
        int[][] a = new int[number][number];
        for(int i=0;i<number;++i){
            a[i][0] = 1;
            a[i][i] = 1;
        }

        for(int i=2;i<number;++i){
            for(int j=1;j<i;++j){
                a[i][j] = a[i-1][j-1] + a[i-1][j];
            }
        }

        for(int i=0;i<number;++i){
            System.out.printf("%" + ((number-i)*2)+ "c",' ');
            for(int j=0;j<=i;++j)
                System.out.printf("%4d",a[i][j]);
            System.out.println();
        }
    }
}
    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/loweir/article/details/46509983
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞