我得到了一个在 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.
到目前为止,她用相反的方法告诉我们,你需要交换数组元素。所以这是我的问题如何交换数组元素以使输入的数组反转?
提前致谢。
更新部分
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/