简体   繁体   中英

what makes it wrong to initialize a variable outside of the while loop?

When I declare the shift outside of while loop, I got the result equals to 16 which is a wrong answer. But when I declare it in the while loop I got the correct answer result == 11. How does the difference change the answer?

long a = Math.abs((long)100);
long b = Math.abs((long)9);
int result = 0;

while (a >= b){
    int shift = 0;
    while(a >= (b<<shift)){
        shift ++;
    }

    a -= b << (shift - 1);
    result += 1 << (shift - 1);
}

Where you declare it doesn't matter, actually - what matters is when and whether you reset the value to zero. For example:

while (a >= b){
    int shift = 0;

and

int shift;
while (a >= b){
    shift = 0;

would be the same for your purposes. But if you instead do this:

int shift = 0;
while (a >= b){

then you aren't resetting shift to 0 at the start of each loop, and would result in a different answer than the first two.

If you define the shift outside the outer while loop, it is initialized only once. So every new iteration of the outer while loop will use the shift-value of last iteration (you do a shift ++ that changes the value), ie 0, 1, 2,...

If you declare the shift inside the outer while loop, it is re-set to 0 on every iteration. Because the result depends on the value of shift, the location of the declaration matters.

When you declare your shift variable out side the loop. It is not being reset to value 0 when iterating each time.

But when you put it in the loop every time your loop is traversed its value is set to zero (more specifically variable is declared again) that makes the output as expected.

Which is not an efficient thing. what I would suggest you to do is declare your variable outside the loop and reset its value in the loop as in the following code

long a = Math.abs((long)100);
long b = Math.abs((long)9);
int result = 0;
int shift = 0;

 while (a >= b){
    shift = 0;
    while(a >= (b<<shift)){
    shift ++;
     }

    a -= b << (shift - 1);
result += 1 << (shift - 1);
}

It is not the declaration of the variable that changes your answer, it's the fact that you set it to 0 every iteration of the outer loop. This is the code you meant to write :

long a = Math.abs((long)100);
long b = Math.abs((long)9);
int result = 0;
int shift = 0;
while (a >= b){
    shift = 0;
    while(a >= (b<<shift)){
        shift ++;
    }

a -= b << (shift - 1);
result += 1 << (shift - 1);
}

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