简体   繁体   中英

I don't understand the solution of this exercise

I am doing an exercise on Practiceit.edu and I have some trouble. The exercise is writing of the following codes:

int total = 25;
for (int number = 1; number <= (total / 2); number++ ) {
    total = total - number;
    System.out.println(total + " " + number );
}

My output is

24 1
22 2
19 3
15 4
10 5
4 6
-3 7
-11 8
-20 9
-30 10
-41 11
-53 12

because i think that number starts at 1 and finish at 12 (number <= (total / 2)). However, the result is

24 1
22 2
19 3
15 4
10 5

I don't understand this result, so can you help me explain it?

The problem is that you are changing the value of total which will be re-evaluated every-time in your loop

try

int total = 25;
int total2 = total;
for (int number = 1; number <= (total / 2); number++ ) {
    total2 = total2 - number;
    System.out.println(total2 + " " + number );
}

output

24 1
22 2
19 3
15 4
10 5
4 6
-3 7
-11 8
-20 9
-30 10
-41 11
-53 12

This is because your total is reducing more and more each time you iterate.

total = total - number;

Ie:

//1st iteration
25 - 1 = 24; // outputs 24 1

// 2nd iteration
24 - 2 = 22 // outputs 22 2

// 3rd iteration
22 - 3 = 19 // outputs 19 3

// 4th iteration
19 - 4 = 15 // outputs 15 4

// 5th iteration
15 - 5 = 10 // outputs 10 5

Etc.

What are you trying to do?

During the final iteration that is printed, total is 10 and number is 5. Once the for loop continues, number increases by 1 and total decreases to 4. The comparison is made between total = 4 / 2 = 2 and number = 6. This result is not printed since the comparison is already made. Thus, you exit the for loop.

The condition used in the for loop says the number is less than or equal to (half of) total

number <= (total / 2)

The last line where that is true is 10 5

Everything after that doesn't satisfy the condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM