首页 > 其他 > 详细

杨辉三角

时间:2016-09-18 08:51:00      阅读:235      评论:0      收藏:0      [点我收藏+]
技术分享
 1 import java.util.Scanner;
 2 import java.util.InputMismatchException;
 3 public class Text2
 4 {
 5     public static void main(String[] args)
 6     {    
 7         System.out.print("我将打印杨辉三角形,并保存到一个数组,请输入一个数字:");
 8         Scanner sc=new Scanner(System.in);
 9         int num=0;
10         try
11         {
12             num=sc.nextInt();
13             if(num>0)
14             {
15                 int[][] array=new int[num][num];
16                 for(int i=0;i<=array.length;i++)
17                 {
18                  int j;
19                     for(j=0;j<=i;j++)
20                     {
21                         if(j==0||i==j)
22                         {
23                                 array[i][j]=1;
24                         }else
25                         {
26                                num=array[i][j]=array[i-1][j-1]+array[i-1][j];
27                         }
28                    if(num<Integer.MAX_VALUE/2)
29                    {    
30                       System.out.print(array[i][j]+"\t");        
31                    }else
32                    {
33                       System.out.println("计算数值过大,为防止程序数值溢出,程序已经强行停止");
34                       break;
35                    }
36                     }
37                     System.out.println();
38                  if(num>=Integer.MAX_VALUE/2)    
39                  {
40                   System.out.println("当前数值为:"+num+"  当前行数为:"+(i+1));
41                   break;
42                  }        
43                 }
44             }else
45             {
46                 System.out.println("请输入一个大于0的正整数");
47             }    
48         }
49         catch(InputMismatchException e)
50         {
51             System.out.println("输入不合法,请输入整数");
52         }
53         
54     }
55 }

杨辉三角

原文:http://www.cnblogs.com/Ivan99999/p/5880311.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!