簡體   English   中英

這段代碼有什么問題? 得到 0 作為答案

[英]What is wrong with this code ? getting 0 as an answer

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 循環。 獲得所需結果的其他方法是什么?

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM