0

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

    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;
}
}

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

提前致谢。

4

2 回答 2

7

你的意思是,num_array[count]而不是num_array[0],我假设。

于 2013-05-03T13:05:37.283 回答
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;
 }
}

将给出正确的输出。

于 2013-05-03T13:12:42.430 回答