TIL One-by-one errors
POSTED ON:
TAGS: math loops javascript codepen
Off by one errors #
An off-by-one error is when you expect something to be of value N, but in reality it ends up being N-1
or N+1
.
For example, you were expecting the program to perform an operation 10 times, but it ends up performing 9 or 11 times (one too few or one too many times).
In programming this is most commonly seen happening when dealing with "for" loops.
let n = 10;
// for (int i = 1; i < n; ++i) { ... }
let countStartAtOne = "0";
for (let i = 1; i < n; ++i) {
countStartAtOne += `, ${i}`;
}
// RESULTS: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
// for (int i = 0; i <= n; ++i) { ... }
let countStartAtZeroGreaterEqual = "0";
for (let j = 0; j <= n; ++j) {
countStartAtZeroGreaterEqual += `, ${j}`;
}
// RESULTS: 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
See the Pen by rockykev (@rockykev) on CodePen.
REF:
https://en.wikipedia.org/wiki/Off-by-one_error
https://stackoverflow.com/questions/2939869/what-is-an-off-by-one-error-and-how-do-i-fix-it
Related TILs
Tagged: math