我正在生成一个随机整数数组,并尝试将值向右移一位,并用前一个元素替换第一个元素。将数组向右移动
输出没有排序,最后一个元素是一个随机生成的整数。
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void shift(int values[], int size) {
int temp;
for (int i = 0; i < size; i++) {
temp = values[size - 1];
values[i] = values[i + 1];
values[0] = temp;
cout << values[i] << setw(4);
}
cout << endl;
}
int main()
{
cout << "Random 10 index array" << endl;
const int CAP = 10;
int numbers[CAP];
srand(time(0));
int i;
for (i = 0; i < CAP; i++) {
int rng = rand() % 100 + 1;
numbers[i] = rng;
cout << numbers[i] << setw(4);
}
cout << "shifting all elements to the right: " << endl;
shift(numbers, CAP);
cout << endl;
system("pause");
return 0;
}
我试过使用i < size - 1
,但是我得到了9个我需要的10个数字。
[你的橡皮鸭子想和你谈谈](https://en.wikipedia.org/wiki/Rubber_duck_debugging)。根据你的橡皮鸭,你的阵列的最后一个元素应该移动到第一个元素一次,作为这个旋转的一部分。这是不言而喻的,你的橡皮鸭想知道你期望如何工作,何时这样做的代码将在每次循环迭代中执行,而不仅仅是一次。看起来,你的代码对你的橡皮鸭根本没有任何意义。 –
我错过了什么,呼叫转移的地方。 – IronMan007
'std :: deque'是比这个应用程序更好的选择。 –