Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

java - Using =+ won't work in for loop

This works:

for(int i = 0; i < size; i++){
    avg[0] = avg[0] + array0[i];
    avg[1] = avg[1] + array1[i];
    avg[2] = avg[2] + array2[i];
    avg[3] = avg[3] + array3[i];
}

However, this doesn't:

for(int i = 0; i < size; i++){
    avg[0] =+ array0[i];
    avg[1] =+ array1[i];
    avg[2] =+ array2[i];
    avg[3] =+ array3[i];
}

In the second example, the array doesn't add to itself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

it's +=, not =+

What you do could be valid code as well, but right now you're doing

avg[0] = + array0[i];

It will work for numeric types (which I assume you have). Simplified example without array index:

int x = +5;

Sample:

public static void main(String[] args) {
    int x = -5;
    int y = +x;
    System.out.println(y); // - + => -

    int a = 5;
    int b = -a;
    System.out.println(b); // + - => -

    int c = 5;
    int d = +5;
    System.out.println(d); // + + => +

    int m = -5;
    int n = -m;
    System.out.println(n); // - - => +
}

Output:

-5
-5
5
5

Copied from comments for clarity:

You're basically saying x = + y. In this case the + is just a matter of indicating it's a positive integer. It's valid code, but it's not what you intend.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...