黑马程序员技术交流社区

标题: 自己写的一个杨辉三角 [打印本页]

作者: 黎健东    时间: 2012-8-12 16:25
标题: 自己写的一个杨辉三角
本帖最后由 黎健东 于 2012-8-12 16:27 编辑
  1. package com.lee.graphic;

  2. public class YangHuiTriangle {

  3.     /**
  4.      * @param args
  5.      */
  6.     public static void main(String[] args) {
  7.         // TODO Auto-generated method stub
  8.         int row = 10;
  9.         int colunm = row * 2;
  10.         int half_colunm = colunm / 2;
  11.         
  12.         int [][]array = new int [row][colunm];
  13.         
  14.         int index = 0;
  15.         for(int i = 0; i < row; i++){
  16.             //左边三角形
  17.             for(int j = 0; j < half_colunm - i - 1; j++){
  18.                 array[i][j] = 0;
  19.                 index++;
  20.             }
  21.             //为单独的1赋值
  22.             array[i][index++] = 1;
  23.             //从第2行起,规律为里边的任意一个数等于上一行的左上+右上
  24.             if(i != 0){
  25.                 //内部三角形
  26.                 for(int k = 0; k < i * 2; k++){
  27.                     if(k % 2 == 0){
  28.                         array[i][index] = 0;
  29.                     }else{
  30.                         array[i][index] = array[i - 1][index - 1] + array[i - 1][index + 1];
  31.                     }
  32.                     index++;
  33.                 }
  34.                 //计算剩余的行
  35.                 int lastColunm = row - index;
  36.                 for(int j = 0; j < lastColunm; j++){
  37.                     array[i][index] = 0;
  38.                     index++;
  39.                 }
  40.             }
  41.             //每一行重置指针index
  42.             index = 0;
  43.             
  44.         }
  45.         //格式输出
  46.         for(int i = 0; i < row; i++){
  47.             for(int j = 0; j < colunm; j++){  
  48.                 if(array[i][j] == 0){
  49.                     System.out.printf("%-3s","");
  50.                 }else{
  51.                     System.out.printf("%-3s",array[i][j]);
  52.                 }
  53.             }
  54.             System.out.println();
  55.         }
  56.         
  57.     }

  58. }
复制代码
自己写的一个杨辉三角
还有需要改进的地方,欢迎拍砖,求加分



作者: 黎健东    时间: 2012-8-13 16:43
花心思不看网上的自己写的,求加1分技术分{:soso_e154:}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2