Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

while loop - What is an off-by-one error and how do I fix it?

What is an off-by-one error? If I have one, how do I fix it?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An off-by-one error is for example when you write intend to perform a loop n times and write something like:

for (int i = 1; i < n; ++i) { ... }

or:

for (int i = 0; i <= n; ++i) { ... }

In the first case the loop will be executed (n - 1) times and in the second case (n + 1) times, giving the name off-by-one. Other variations are possible but in general the loop is executed one too many or one too few times due to an error in the initial value of the loop variable or in the end condition of the loop.

The loop can be written correctly as:

for (int i = 0; i < n; ++i) { ... }

A for loop is just a special case of a while loop. The same kind of error can be made in while loops.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...