我已经编写了这段代码来尝试和反转给定数组中的元素:
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
int numbers[6] = {1, 5, 9, 10, 12, 18};
int b = 0;
int a = 5;
for (int i = 0; i < 3; ++i)
{
b = numbers[i];
numbers[i] = numbers[a-i];
numbers[a-i] = b;
}
for(int c = 0; c < 6; ++c)
cout << *(numbers) << endl;
return 0;
}它应该打印出18,12,10,9,5,1,但是当我运行程序时,它只打印出18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,我哪里出错了?我猜这是第一个for循环中的问题。谢谢你的帮助。
发布于 2013-03-03 20:57:32
更改cout << *(numbers) << endl;
转到cout << numbers[c] << endl;
再加上使用<algorithm>头文件中的标准reverse算法:
std::reverse(numbers, numbers+6);发布于 2013-03-03 20:57:11
这是第二个for循环,你忘了加c。
for(int c = 0; c < 6; ++c)
cout << *(numbers + c) << endl;发布于 2013-03-03 22:05:31
您可以尝试这样做:
for(int i = 0; i < ARRAY_SIZE; ++i) {
//a^=b^=a^=b; //SWAP a with b
numbers[i] ^= numbers[ARRAY_SIZE-i] ^= numbers[i] ^= numbers[ARRAY_SIZE-i];
}它将反转数组中的所有元素。:)
https://stackoverflow.com/questions/15185880
复制相似问题