在大多数编程语言中,从 0
开始的数组索引的目的是什么,与我们引用大多数 IRL 事物(第一、第二、第三等)的顺序方式相比?这背后的逻辑或效用是什么?
我现在已经完全习惯了,但从未停下来思考背后的原因。
更新 :我从谷歌上读到的一个好处是,如果你想升级到 i < n
,for 循环可以有 n
。
最佳答案
Dijkstra 在 Why numbering should start at zero 中列出了推理。
When dealing with a sequence of length N, the elements of which we wish to distinguish by subscript, the next vexing question is what subscript value to assign to its starting element...
when starting with subscript 1, the subscript range 1 ≤ i < N+1; starting with 0, however, gives the nicer range 0 ≤ i < N. So let us let our ordinals start at zero: an element's ordinal (subscript) equals the number of elements preceding it in the sequence. And the moral of the story is that we had better regard —after all those centuries!— zero as a most natural number.
关于math - 从 0 开始数组的好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8526525/