Closed KLYkl closed 4 months ago
Hi,i
定义为索引,因此输入应该在区间 [0, capacity())
内,不应出现负数的情况。
严谨的做法是在 index()
方法中添加安全判断,保证输入参数 i
满足索引范围。但为了简洁性,书中代码会省略部分安全判断等代码。
Hi, 定义为索引,因此输入应该在区间 内,不应出现负数的情况。
i``[0, capacity())
严谨的做法是在 方法中添加安全判断,保证输入参数 满足索引范围。但为了简洁性,书中代码会省略部分安全判断等代码。
index()``i
这么说那i%capacity()就可以了,不必写(i + capacity()) % capacity()了吧?
将43行的return (i + capacity()) % capacity();改为return (i % capacity() + capacity()) % capacity(); 原因:原来的表达式“(i + capacity()) % capacity();”如果i是负数的话,需要保证capacity() >= -i。而更改后的表达式“ (i % capacity() + capacity()) % capacity();” 中的先对i取模相加,最后再取模操作会确保结果是一个非负整数,并且不会超过 capacity() 的值。这是因为取模操作会返回一个在 0 到 capacity() - 1 范围内的数,即使原始的和可能是负数。保证函数index()的传入形参i<-capacity()不会崩溃,且能正确返回 0 到 capacity() - 1 范围内的的索引值。
If this pull request (PR) pertains to Chinese-to-English translation, please confirm that you have read the contribution guidelines and complete the checklist below:
If this pull request (PR) is associated with coding or code transpilation, please attach the relevant console outputs to the PR and complete the following checklist: