java - 为什么输出的结果为4321?
黄舟
黄舟 2017-04-18 10:49:09
0
4
710
Char  c[]={'1','2','3','4'}
for(int i=0;i<c.length/2;i++){
    char d=c[i];
    c[i]=c[c.length-(i+1)];
    c[c.length-(i+1)]=d;
}
for(int i=0;i<c.length;i++){
    System.out.println(c[i]);
}

为什输出的结果为4321?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(4)
Peter_Zhu

Loop twice, the first time 1 and 4 are exchanged, the second time 2 and 3 are exchanged

Peter_Zhu

Why not? '1' and '4' are swapped, '2' and '3' are swapped.

伊谢尔伦

When i = 0;
char d=c[i];char d=c[i];
将c[0]的值赋值给d, 也就是1;
此时c数组依旧是[1, 2, 3,4],但d有了初始值,为1;
【操作的含义是将交换的A方放在空闲位置】
c[i]=c[c.length-(i+1)];
将c[3]的值赋予c[0];
此时c数组是[4,2,3,4], d值为1;
【操作的含义是将交换的B方的值给A方】
c[c.length-(i+1)]=d;Assign the value of c[0] to d, which is 1;
At this time, the c array is still [1, 2, 3, 4], but d has an initial value, which is 1;
[The meaning of the operation is to place the exchanged A side in a free position]
c[i]=c[c.length-(i+1 )];

Assign the value of c[3] to c[0];

At this time, the c array is [4,2,3,4], and the d value is 1;
[The meaning of the operation is to exchange Give the value of side B to side A】char d=c[i];
d为c[1], 也就是2;
此时c数组为[4,2,3,1], d值为2;
c[i]=c[c.length-(i+1)];
将c[2]的值赋予c[1];
此时c数组为[4,3,3,1],d值为2;
c[c.length-(i+1)]=d;c[c.length-(i+1)]=d;
Change the value of d, which is the value of c[0] at the beginning to 1, Assign a value to c[3];
So far, the value of the c array is [4,2,3,1], and the d value is 1;

[The meaning of the operation is to change the number of free positions, that is, the initial value of A , to B; finally realize the exchange of the values ​​​​of A and B]

When i is 1, 🎜char d=c[i];🎜d is c[1], which is 2; 🎜At this time, the c array is [4,2,3,1] , d value is 2;🎜c[i]=c[c.length-(i+1)];🎜Assign the value of c[2] to c[1];🎜At this time, c The array is [4,3,3,1], and the d value is 2; 🎜c[c.length-(i+1)]=d;🎜Change the value of d, that is, at the beginning The value of c[1] is 2, assigned to c[2]; 🎜At this time, the c array is [4,3,2,1], and the d value is 2;🎜 🎜End the first for loop; 🎜
小葫芦

Essentially it is a swap operation
Example
a = 1 b = 2 => c = b => b = a a = c
If it can be like this:
a =1 ,b = 2;
a,b:= b,a;
Looks simpler

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template