说我有数组
{0, 1, 2, 3, 4}
- 索引 0 和 4 是相反的
- 索引 1 和 3 是相反的
- 索引 2 的对面未定义
或者
{0, 1, 2, 3, 4, 5}
- 索引 0 和 5 是相反的
- 索引 1 和 4 是相反的
- 索引 2 和 3 是相反的
我记得看到一个非常聪明的方法来做到这一点。就像是
i%array.length
说我有数组
{0, 1, 2, 3, 4}
或者
{0, 1, 2, 3, 4, 5}
我记得看到一个非常聪明的方法来做到这一点。就像是
i%array.length
试试这个:
oppIndex = array.length - firstIndex - 1;
array = {1, 2, 3, 4, 5}
idx = 0 /* 0 is the first array position with value of 1 */
IF array.length - idx - 1 > idx
RETURN array[ array.length - idx - 1 ] /* returns array[4] == 5 */
ELSE
RETURN undefined
array = {1, 2, 3, 4, 5}
idx = 2 /* 2 is the third array position with value of 3 */
IF array.length - idx - 1 > idx /* 5 - 2 - 1 == 2 which is NOT greater than 2 */
RETURN array[ array.length - idx - 1 ]
ELSE
RETURN undefined
按照您的第一个示例逻辑...
if (array.length%2==0){
for (int i =0; i<array.length/2; i++){
syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
}
}
else {
for (int i =0; i<floor(array.length/2); i++){
syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
}
i = i+1
syso("the opposite of "+ array[i] +" is undefined"
}