zoukankan      html  css  js  c++  java
  • 0915作业-----改进后的杨辉三角形---过滤掉非法输入---简单过滤掉数值溢出

     

      

     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]+"	");        
    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 }
  • 相关阅读:
    hdu 4002 Find the maximum
    hdu 2837 坑题。
    hdu 3123
    zoj Treasure Hunt IV
    hdu 2053 Switch Game 水题一枚,鉴定完毕
    poj 1430 Binary Stirling Numbers
    hdu 3037 Saving Beans
    hdu 3944 dp?
    南阳oj 求N!的二进制表示最低位的1的位置(从右向左数)。
    fzu 2171 防守阵地 II
  • 原文地址:https://www.cnblogs.com/kaililikai/p/5876581.html
Copyright © 2011-2022 走看看