这段代码有什么问题?获得0作为答案

时间:2015-10-07 18:17:29

标签: java computer-science

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);
}

我得零是什么问题? 我只能用于这个循环。 有什么方法可以获得所需的结果?

1 个答案:

答案 0 :(得分:-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);

}