2016-09-18 71 views
-8

編寫一個程序,將n1至n2中的所有正數(包括兩端)合計並存儲在變量n中。你的程序應該打印出消息「n2 - n1數字的總和」,然後是總和(n)的值。在Java中查找給定整數範圍(僅限正數)

現在,這是我的代碼:

/*您在這裏的代碼*/

import java.util.Scanner; 
class NumSum{ 
    public static void main(String args[]){ 
     int n=0;   
     System.out.println("The sum of n2-n1 numbers is "+sum(n)); 
    } 
    public static int sum(int n){ 
     int n1,n2; 

     Scanner sc=new Scanner(System.in); 
     n1=sc.nextInt(); 
     n2=sc.nextInt(); 
     int a=n1; 
     n=n2-n1+1; 
     int d=1; 
     int x=0; 
     //if(n1>0&&n2>0){ 
      // for(int i=n1;i<=n2;i++){ 
      //  n+=i; 
      // } 
     //}else 
     if(n1<0&&n2>0){ 
      x=n*(2*a+(n-1)*d)/2;    
     }else if(n1>0&&n2>0){ 
      x=n*(2*a+(n-1)*d)/2; 
     }else if(n1<0&&n2<0){ 
      x=0; 
     }else if(n1>0&&n2<0){ 
      x=0; 
     } 
     return x; 
    } 
} 

但它不接受上述問題給出的測試案例? 任何人都可以幫忙嗎?

enter image description here

+1

如果n1> n2會怎麼樣? – Eran

+4

不接受是什麼意思? –

+0

我不知道測試用例是什麼問題! –

回答

0

因爲這只是你應該添加的正數,讓n1 = 0如果n1爲負。找到第一個n號碼的總和的公式爲(n^2+n)/2。 在應用公式之前,下限(n1)應減少1,因爲限制包括在總和中。

import java.util.Scanner; 
class NumSum{ 
    public static void main(String args[]){ 

     System.out.println("The sum of n2-n1 numbers is "+sum()); 
    } 
    public static int sum(){ 
      int n1,n2; 

     Scanner sc = new Scanner(System.in); 

     n1=sc.nextInt(); 
     n2=sc.nextInt(); 

     int tmp; 

     if(n1 > n2) 
     { 
      tmp = n1; 
      n1 = n2; 
      n2 = tmp; 
     } 

     n1--; 

     if(n1<0) 
      n1 = 0; 
     if(n2<0) 
      return 0; 


     int sum1 = (n1*n1 + n1)/2; 
     int sum2 = (n2*n2 + n2)/2; 

     return sum2 - sum1; 

    } 
} 
+0

測試用例仍未通過! –

+0

關於'n1'和'n2'的問題中給出的任何限制? – pahan

+0

現在看到上面的圖片! –

-1

如果你想從一個總結範圍內的整數B(含; A和B允許爲正數,負數;一個< = B),把它作爲一個系列:

a+0, a+1, a+2, .... a+k (b is conviniently termed as a+k) 

各部分可以作爲來概括:

(k+1)*a + k(k+1)/2 

消除K,給你下式:

[(b-a+1)(a+b)]/2 

當b> a時,您需要交換a和b。

請注意java的整數部分。如果您有其他例外情況,請在此修改公式。

class NumSum { 
    public static int sum_range(int a, int b) { 
     if (a>b) return(sum_range(b,a)); 
     return(((b-a+1)*(a+b))/2); 
    } 

    public static void main(String args[]) { 
     int i=Integer.parseInt(args[0]); 
     int j=Integer.parseInt(args[1]); 
     System.out.println("Sum: " + sum_range(i,j)); 
    } 
}