什么是逐一错误,我该如何解决? [英] What is an off-by-one error and how do I fix it?

查看:26
本文介绍了什么是逐一错误,我该如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是逐一错误?如果我有,我该如何解决?

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

推荐答案

An off-by-one error 例如,当您编写打算执行 n 次循环并编写如下内容时:

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) { ... }

或:

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

在第一种情况下,循环将执行 (n - 1) 次,在第二种情况下将执行 (n + 1) 次,给出名称 off-by-一.其他变化也是可能的,但通常由于循环变量的初始值或循环结束条件中的错误,循环执行次数过多或过少.

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.

循环可以正确写成:

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

for 循环只是 while 循环的一个特例.在 while 循环中也会出现同样的错误.

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

这篇关于什么是逐一错误,我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆