【发布时间】:2021-04-26 10:10:23
【问题描述】:
int main()
{
int newposition, shiftSteps;
int numbers[10], numberscopy[10];
cin >> shiftSteps;
for (int i = 0; i < 10; i++)
cin >> numbers[i];
for (int i = 0; i < 10; i++)
numberscopy[i] = numbers[i];
//------------------------------------
for (int i = 9; i >= 0; i--)
{
if (i - shiftSteps < 10 && i - shiftSteps >= 0)
newposition = i - shiftSteps;
else
newposition = i - shiftSteps + 10;
numbers[newposition] = numberscopy[i];
}
for (int i = 0; i < 10; i++)
cout << numbers[i] << " ";
}
我想向左旋转 10 个数字,"shiftSteps" 是向左移动的次数。但是我有一个问题,到目前为止,我为某些数字编写的代码可以正常工作,例如{0 1 2 3 4 5 6 7 8 9} and shiftSteps = 3 输出为3 4 5 6 7 8 9 0 1 2。
但如果输入为0 1 2 3 4 5 6 7 8 9 和shiftSteps = 15,则输出为5 6 7 8 9 5 6 7 8 9 和0 消失,shiftSteps = 15 的正确答案是5 6 7 8 9 0 1 2 3 4。
【问题讨论】:
-
在您的示例中,
shiftSteps未初始化。 -
std::rotate会做你想做的事。 -
@GaryNLOL:OP 代码中没有
using namespace std;。可能是using std::cin;:)