An off-by-one error (OBOE) is a logic error involving the discrete equivalent of a boundary condition. It often occurs in computer programming when an iterative loop iterates one time too many or too few. Usually this problem arises when a programmer fails to take into account that a sequence starts at zero rather than one (as with array indices in many languages), or makes mistakes such as using "is less than or equal to" where "is less than" should have been used in a comparison. This can also occur in amathematical context.
Src: http://en.wikipedia.org/wiki/Off-by-one_error
Consider an array of items, and items m through n (inclusive) are to be processed. How many items are there? An intuitive answer may be n−m, but that is off by one, exhibiting a fencepost error; the correct answer is n−m+1.
For this reason, ranges in computing are often represented by half-open intervals; the range from m to n (inclusive) is represented by the range from m (inclusive) to n+1(exclusive) to avoid fencepost errors. For example, a loop that iterates five times can be written as a half-open interval from 0 to 5:
for (i = 0; i < 5; i++) { /* Body of the loop */ }
Src: http://en.wikipedia.org/wiki/Off-by-one_error
Комментариев нет:
Отправить комментарий