请帮我解释一下这个程序的思路!谢谢

来源:百度知道 编辑:UC知道 时间:2024/05/15 02:28:11
题目:数组中有n个数据,要将它们顺序循环后移k位,例如0,1,2,3,4循环后移3位后为2,3,4,0,1。

#include <iostream>
using namespace std;
int main ()
{

int array[5] = {0, 1, 2, 3, 4};
int n ;
cin >> n;
int j = 0;
int res = array[j];
for (int i=0; i<5; i++)
{
int temp = res;
res = array[(j+3)%5];
array[(j+3)%5] = temp;
j = (j+3) % 5;
}
for (i = 0; i<5 ;i++)
cout << array[i];

}

请解释一下这个程序的思路!

各步循环的运行结果:
j...temp...res...(array)0...1...2...3...4
0....0......0...........0...1...2...3...4...未进入循环
3....0......3.......................0.......i=0
1....3......1...............3...............i=1
4....1......4...........................1...i=2
2....4......2...................4...........i=3
0....2......0...........2...................i=4
........................2...3...4...0...1...最后结果
中间程序你应该有删节
慢慢分析不难的,在张纸上画个表
记得每次分析的时候先计算出(j+3)%5的数值,耐心点就可以的