我有一个带有数组的函数,以及随机的头尾索引值。我试图从尾值向后遍历整个数组,直到头值,但似乎有些值被跳过。
这是我的逻辑:
currentRec = tail;
while (currentRec != head)
{
// get current record from array and do stuff (i.e. myArray[currentRec])
if (currentRec == 0)
{
currentRec = MAX_RECORDS - 1; // MAX_RECORDS is 200
}
else
{
currentRec--;
}
}
我错过了什么或做错了什么?
答案 0 :(得分:2)
您的循环未处理索引head
处的最终元素。如果您要处理从tail
到head
包含的所有元素,那么您需要稍微更改一下逻辑:
currentRec = tail;
while (1)
{
// get current record from array and do stuff (i.e. myArray[currentRec])
if (currentRec == head) // if we've just processed the last (i.e. head) element
{
break; // exit loop
}
if (currentRec == 0) // otherwise bump currentRec and repeat...
{
currentRec = MAX_RECORDS - 1; // MAX_RECORDS is 200
}
else
{
currentRec--;
}
}
<小时/> 的更新强>
如果你有额外的要求,当head == tail
然后你想要处理数组中的所有元素时,你需要添加更多的逻辑:
currentRec = tail;
done = false;
while (1)
{
// get current record from array and do stuff (i.e. myArray[currentRec])
if (done) // if we've just processed the last (head) record
{
break; // exit loop
}
if (currentRec == 0)
{
currentRec = MAX_RECORDS - 1; // MAX_RECORDS is 200
}
else
{
currentRec--;
}
if (currentRec == head)
{
done = true; // set flag to indicate that the next iteration will be the last
}
}