代码改变世界

Java错误2(2015-8-27)

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

1、求1!+5!+9!+...+21!之和。

public class FourTest{

 public static void main(String[] args){  

                    double sum = 0;   

                    double jc_sum = 1;   //如果说是long数据类型,结果是负数。是内存溢出。

                    for(int i=1;i<=21;i=i+4){  

                           //-每一个阶乘之和   

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

                                       jc_sum = jc_sum*j;   

                           }   

                           sum = sum + jc_sum;  

                           //--初始化每个阶乘的和   

                            jc_sum = 1;     

                    }   

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

 } }

2、public class Test3{
       public static void main(String [] args){
                        
           double sum=0;
           double jc=1;
           for(int i=1;i<=21;i++){
                     for(int j=1;j<=i;j++){
                         jc=jc*j;
                     }
                     if(i % 4 == 1){
                         sum=sum+jc;
                        
                     }
                     jc=1;
           }
           System.out.println("求1!+5!+9!+...+21!之和是:"+sum);
}}