用简单的c++写一个代码,1 . 数据移位 有n(n<=10)个整数,使前面各数顺序向后移m (m<=n)个位置,最后m个数变成最前面的m个数,如图所示。编写函数shift(a,n,m)实现上述功能,在主函数中输入n个整数并输出调整后的n个数。 SAMPLE OUTPUT Input n(n<=10):10 Input 10 integers:123456789 10 Output the original:123456789 10 Input m(m<=10):4 Output the shifted:789 10123456
时间: 2023-12-14 10:40:13 浏览: 31
以下是C++的代码实现:
```c++
#include <iostream>
using namespace std;
void shift(int a[], int n, int m) {
int temp[m];
for (int i = n - m; i < n; i++) {
temp[i - (n - m)] = a[i]; // 保存最后m个数
}
for (int i = n - m - 1; i >= 0; i--) {
a[i + m] = a[i]; // 将前面n-m个数往后移m位
}
for (int i = 0; i < m; i++) {
a[i] = temp[i]; // 将保存的最后m个数放到最前面
}
}
int main() {
int n;
cout << "Input n(n<=10):";
cin >> n;
int a[n];
cout << "Input " << n << " integers:";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cout << "Output the original:";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
int m;
cout << "Input m(m<=10):";
cin >> m;
shift(a, n, m);
cout << "Output the shifted:";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
```
输入样例:
```
Input n(n<=10):10
Input 10 integers:1 2 3 4 5 6 7 8 9 10
Input m(m<=10):4
```
输出样例:
```
Output the original:1 2 3 4 5 6 7 8 9 10
Output the shifted:7 8 9 10 1 2 3 4 5 6
```