数组执行问题困扰我 [英] Array execution question which confused me

查看:129
本文介绍了数组执行问题困扰我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们获得以下代码:



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}

推荐答案

通过调试器运行它会变得清晰。

i随着循环的每次传递而变化:0,1,2,3,4

因此,您将值放入的元素从第一个开始,然后继续到第二个,依此类推。

值也会改变,但它始于:

Run it through the debugger and it'll become clear.
i varies with each pass through the loop: 0, 1, 2, 3, 4
So the element you put the value into starts with teh first and moves on to teh second, and so on.
The value changes as well, but it starts with:
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!


您应该学习尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



逐行执行程序并在程序执行时检查变量

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

Execute the program line by line and inspect variables as the program executes
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.


这篇关于数组执行问题困扰我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆