zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    在命令提示符中使用antlr
    Migrating to Rails 2.0.2
    从AJAX IN ACTION书中学用 RSS READER
    maple download url
    搜索
    发邀请在线RoR开发与部署环境www.heroku.com
    if can't use ruby in command line
    查询表中某字段有重复记录的个数
    WPF窗体自适应分辨率
    《思考,快与慢》
  • 原文地址:https://www.cnblogs.com/bors/p/yh.html
Copyright © 2011-2022 走看看