反向数组不是顺序的

时间:2013-05-03 13:03:36

标签: c++ arrays swap

我试图反转数组中的元素。例如,我得到了:

    15 69 94 52 97 51 17 18 50 18

它会在:

    18 50 18 17 51 97 52 94 69 15 (which is reversed)

然而,这是我从我的代码中获得的:

    51 69 94 52 97 17 18 50 18 15 (the sequence are jumbled out which I have no idea why)

这是我的代码:

     void reverse(int num_array[], const int& size);
int main ()
{
const int size = 10;
int num_array[size];

srand (time(NULL));

for (int count = 0; count< size ; count++){
    /* generate secret number between 1 and 100: */
    num_array[count] = rand() % 100 + 1;
    cout << num_array[count] << " " ;
}

reverse(num_array,size);

cout << "\n\n" ;
for(int index = 0; index< size; index++){
    cout << num_array[index] << " " ;
}

cout << endl;

system("PAUSE");
return 0;
}

void reverse(int num_array[], const int& size)
{
for (int count =0; count< size/2; count++){
    int temp = num_array[0];
    num_array[0] = num_array[size-count-1];
    num_array[size-count-1] = temp;
}
}

我猜我的反向方法有问题。有人可以解决它吗?

提前致谢。

2 个答案:

答案 0 :(得分:7)

我的意思是num_array[count]而不是num_array[0]

答案 1 :(得分:1)

void reverse(int num_array[], const int& size)
{
 for (int count =0; count< size/2; count++){
 int temp = num_array[count];
 num_array[count] = num_array[size-count-1];
 num_array[size-count-1] = temp;
 }
}

会给出正确的输出。