2015-10-07 60 views
-4
public class Sum { 
public static void main(String[]args){ 
    int sumOfPos = 0; 
    int sumOfNeg = 0; 
    int sum = sumOfPos + sumOfNeg; 
//should give 1 , 5 , 9 
     for(int pos = 1 ; pos<= 9; pos+=4){ 
      int Old = pos*pos; 
      sumOfPos = pos + Old; 
     } 
//should give -3 and -7 
     for(int neg = -3 ; neg>= -7; neg-=4){ 
      int Old = neg*neg; 
      sumOfNeg = neg + Old; 
     } 
// should give the sum of the sqaure of these numbers 
    System.out.println(sum); 
} 

我得到零是什麼問題? 我只能用這個for循環。 獲得所需結果的其他方法是什麼?這段代碼有什麼問題?得到0作爲答案

+1

你覺得呢'INT總和= sumOfPos + sumOfNeg;'呢?你爲什麼這麼認爲? –

+0

應該添加它們嗎? –

+0

但是,當'sumOfPos'和'sumOfNeg'仍然爲0時,您正在設置'sum'的值。此後,您絕不會更新'sum'。 – jaredk

回答

-1
public class Sum { 
    public static void main(String[]args){ 
     int sumOfPos = 0; 
     int sumOfNeg = 0; 
//should give 1 , 5 , 9 
    for(int pos = 1 ; pos<= 9; pos+=4){ 
     int Old = pos*pos; 
     sumOfPos = pos + Old; 
    } 
//should give -3 and -7 
    for(int neg = -3 ; neg>= -7; neg-=4){ 
     int Old = neg*neg; 
     sumOfNeg = neg + Old; 
    } 
// should give the sum of the sqaure of these numbers 
int sum = sumOfPos + sumOfNeg; 
System.out.println(sum); 

}

+0

所以這個工作? –

+3

你告訴我們。如果它不起作用,那麼你不應該發佈這個答案。 – jaredk