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

后端 未结 5 1050

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

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 09:13

    A common off-by-one confusion arises because some languages enumerate vectors from zero (C, for example) and other languages from one (R, for example). Thus, a vector x of size n has members running from x[0] to x[n-1] in C but from x[1] to x[n] in R.

    You are also confronted with the off-by-one challenge when coding the common idiom for cyclic incrementation:

    In C:

    i = (i+1)%n
    

    In R:

    i <- (i-1)%%n + 1
    

提交回复
热议问题