完整题干:
有n个整数,使前面各数顺序向后移m个位置,最后m个数变成最前面m个数,见图6.25。写一函数实现以上功能,在主函数中输入n个整数,并输出调整后的n个数。
个人答案:
#include <iostream>
using namespace std;
void move(int* s, int m, int n);//定义一个移动函数
int main()
{
int a[10], i, num;
for (i = 0, cout << "Please enter 10 numbers: "; i < 10; cin >> a[i++]);
cout << "Please enter move number: ";
cin >> num;
while (num < 0 || num>10) //当没有输数或数字大于10个时
{
cout << "Error! Retry!\nPlease enter 10 numbers: ";
cin >> num;
}
move(a, num, 10);
for (i = 0, cout << "New line: "; i < 10; cout << a[i++] << ' ');//输出新的数列
cout << endl;
system("pause");
return 0;
}
void move(int* s, int m, int n)//定义一个移动函数
{
int i, j, t[10];
for (i = n - m, j = 0; i < 10; t[j++] = *(s + i++));
for (i = n - m - 1, j = n - 1; i >= 0; *(s + j--) = *(s + i--));
for (i = 0; i < m; *(s + i) = *(t + i), i++);
}
结果: