代码改变世界

Java错误1(2015-8-27)

2015-08-27 15:22  马尔代夫_珍  阅读(193)  评论(0编辑  收藏  举报

1、

public class FourTest{

 public static void main(String[] args){  

              long sum = 0;  

              long jc_sum = 1;//该处必须是long数据类型。如果是int,jc_sum=20!的话,会丢失精度。都必须是long数据类型。

              for(int i=1;i<=20;i++){    

                           for(int j=1;j<=i;j++){    

                                         jc_sum = jc_sum*j;   

                           }   

                            sum = sum + jc_sum;     //将jc_sum=n!的值赋值给sum.

                            jc_sum = 1;     //然后必须要将jc_sum赋值为1.

               }  

               System.out.println("sum:"+sum);

 } }

2、

public class Test3{    

    public static void main(String [] args{                                                         

               long sum=0;           

               long jc=1;

               for(int i=1;i<=20;i++){                 

                              for(int j=1;j<=i;j++){                 

                                                jc=jc*j;                                                

                               }              

                              sum=sum+jc;             

                              jc=1;//-----------关键点,重新赋值1。否则计算结果不对。        

               }                                   

                System.out.println("求1!+2!+3!+...+20!之和是:"+sum);

}}

3、

public class Test33{      

  public static void main(String[] args){           

                   System.out.println("1!+2!+3!+……+20!="+getSum(20));     

   }        

   public static long getSum(int n){           

                    long fac=1;          

                    long sum=0;        

                    for(int i=1;i<=n;i++){                     

                                   for(int k=1;k<=i;k++){                  

                                                     fac=fac*k;               

                                    }                                      

                                   sum=sum+fac;                    

                                   fac=1;              

                    }           

                    return sum;

} }