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

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

问题描述

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

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

推荐答案

关闭-一个错误例如,当您编写打算执行一次循环并编写类似以下内容的内容时:

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)次,从而将名称逐个分开.其他变化也是可能的,但是由于循环变量的初始值或循环的结束条件存在错误,因此循环通常执行一次或执行一次或多次.

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天全站免登陆