zoukankan      html  css  js  c++  java
  • 杨辉三角(用for循环)

     1 public class Test413__________________ {
     2     public static void main(String[] args) {
     3         int rows = 10;
     4         for (int i = 0; i < rows; i++) {
     5             int number = 1;
     6             // 打印空格字符串
     7             System.out.format("%" + (rows - i) * 2 + "s", "");
     8             for (int j = 0; j <= i; j++) {
     9                 System.out.format("%4d", number);
    10                 number = number * (i - j) / (j + 1);
    11             }
    12             System.out.println();
    13         }
    14     }
    15 }

    上面使用了格式化输出,看不懂看下面的。

     1 public class Test413_19 {
     2     public static void main(String[] args) {
     3         Scanner input = new Scanner(System.in);
     4         System.out.println("请输入杨辉三角的行数");
     5         int n = input.nextInt();
     6         yhs(n);
     7         input.close();
     8     }
     9     public static void yhs(int n) {
    10         int h;
    11         for (int i = 0; i < n; i++) {
    12             h = 1;
    13             for (int k = i; k < n - 1; k++) {
    14                 System.out.print("  ");
    15             }
    16             for (int j = 0; j <= i; j++) {
    17                 System.out.format("%4d", h);
    18                 h = h * (i - j) / (j + 1);
    19             }
    20             System.out.println();
    21         }
    22     }
    23 }
     System.out.format("%4d", h);
      这个是为了让数字之间对齐。
      这两个代码都是用的同一种算法,只是输出方式不同。
  • 相关阅读:
    关于拷贝构造函数和赋值运算符
    笔试题(转)
    Pro *C/C++学习笔记(一)
    __cdecl
    Visual Studio 2010中C++的四大变化(转)
    小小递归函数的执行过程
    stl string常用函数
    【C/C++ string】之strcpy函数
    409 Excuses, Excuses!
    10878 Decode the tape
  • 原文地址:https://www.cnblogs.com/fzxey/p/10723987.html
Copyright © 2011-2022 走看看