gpt4 book ai didi

c++ - 交换数组中的元素以反转数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:40 26 4
gpt4 key购买 nike

我得到了一个在 C++ 中反转动态数组的作业。到目前为止,根据我的逻辑,我想通过数组循环来反转它。这是我的代码:

int main ()
{
const int size = 10;
int num_array[size];

srand (time(NULL));

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

reverse(num_array[size],size);

cout << endl;

system("PAUSE");
return 0;
}

void reverse(int num_array[], int size)
{
for (int count =0; count< sizeof(num_array)/sizeof(num_array[0]); count++){
cout << num_array[sizeof(num_array)/sizeof(num_array[0])-1-count] << " " ;
}

return;
}

不知何故,我认为我的逻辑在那里,但这段代码不起作用,有一些错误。但是,我的老师告诉我,这不是问题想要的方式。这是问题:

    Write a function reverse that reverses the sequence of elements in an array. For example, if reverse is called with an array containing 1 4 9 16 9 7 4 9 11,
then the array is changed to 11 9 4 7 9 16 9 4 1.

至此,她用reverse的方法告诉我们,你需要交换数组元素。所以这是我的问题如何交换数组元素以便反转输入的数组

提前致谢。

更新部分

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

system("PAUSE");
return 0;

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

最佳答案

reverse 函数应该如下所示:

void reverse(int* array, const size_t size)
{
for (size_t i = 0; i < size / 2; i++)
{
// Do stuff...
}
}

然后这样调用它:

reverse(num_array, size);

关于c++ - 交换数组中的元素以反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16356183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com