问题描述
假设我们获得以下代码:
int [] myArray = {4,5,6,1,2,3,21,20} ;
for(int i = 0; i< 5; i ++){
myArray [i] = myArray [length -1 - i];
}
执行后,myArray数组包含哪些内容?
我尝试了什么:
我不确定这个问题的长度意味着什么。如果长度意味着5,我认为答案是{0,-1,-2,3,2,1,-17,-16}。如果length表示此Array中有多少值,则应为8,答案应为{3,2,1,6,5,4,-14,-13}
Suppose that we are given the following code:
int[] myArray = {4, 5, 6, 1, 2, 3, 21, 20};
for (int i = 0; i < 5; i++) {
myArray[i] = myArray[length -1 - i];
}
After it is executed what will the array myArray contain?
What I have tried:
I am not sure what length means in this question. If length means 5, I think the answer is{0, -1, -2, 3, 2, 1, -17, -16}. If length means how many value in this Array, it should be 8, the answer should be {3, 2, 1, 6, 5, 4, -14, -13}
推荐答案
myArray[length -1 - 0]
然后使用
And then uses
myArray[length -1 - 1]
等等。
所以if长度为5(对myArray来说是错误的 - 它应该是8)然后你加载的索引是4,3,2,1,0
所以元素0变为元素4:2
元素1变为元素3:1
元素2变为元素2:6
元素3变为元素1(其中已经改变了):1
Elem ent 4成为元素0(已更改):2
说真的:使用调试器,你会看到我的意思!
And so forth.
So the if length is 5 (which is wrong for myArray - it should be 8) then the indexes you load from are 4, 3, 2, 1, 0
So element 0 becomes element 4: 2
Element 1 becomes element 3: 1
Element 2 becomes element 2: 6
Element 3 becomes element 1 (which has changed): 1
Element 4 becomes element 0 (which has changed): 2
Seriously: use the debugger and you'll see what I mean!
int tmp;
int[] myArray = {4, 5, 6, 1, 2, 3, 21, 20};
for (int i = 0; i < 5; i++) {
tmp= length -1 - i;
myArray[i] = myArray[length -1 - i];
}
tmp只会显示下一行获取值的位置。
The tmp will just show you where it get the value in next line.
这篇关于数组执行问题困扰我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!