简体   繁体   中英

Control flow in a while loop

When solving a question of Project Euler I ran into the following logical error related to when n is updated.

while(n<1000):
    #update n
    #do something with n
    #do stuff

vs

while(n<1000):
    #do something with n
    #do stuff
    #update n

In the first instance, I ended up performing an operation with n even though the condition of n<1000 is violated.

Does this logical error have a name? How common is this bug?

I tried to look for it, I did find things about pre-incrementing and post-incrementing a variable. Although that is close to the error, it isn't exactly what is happening here. I found a reference to this in a SO answer about for loop vs while loop in the part describing how for loops are more concise and direct when compared to while loops. Essentially with while loops we end up running code after a variable update which could be buried somewhere in the code.

This is not always a bug: it depends on the algorithm. In some cases, you know that the original value of n is legal (so you can enter the loop), but you want to update and use the new value in your processing. You need to match your code to your algorithm. Your second code block is the canonical for -equivalent, and is more common.

This falls under the general heading of "off by 1 error".

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