C语言有n个整数,使前面各数顺序向后移m个位置,最后m个数变成前面m个数,见图。写一函数:实现以上功能,在主函数中输入n个数和输出调整后的n个数。
时间: 2024-06-14 22:05:02 浏览: 7
以下是一个实现C语言中将前面的数顺序向后移动m个位置的函数:
```c
#include <stdio.h>
void move(int a[], int n, int m) {
int *p_head = a;
int *p_end = a + n - m;
int temp;
while (p_head < p_end) {
temp = *p_head;
*p_head = *p_end;
*p_end = temp;
p_head++;
p_end++;
}
}
int main() {
int n, m;
printf("你要输入多少个数?");
scanf("%d", &n);
int a[n];
printf("输入%d个数:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("你想将最后多少个数前移?");
scanf("%d", &m);
move(a, n, m);
printf("排好了:\n");
for (int i = 0; i < n; i++) {
printf("%d,", a[i]);
}
return 0;
}
```
相关问题
有n个整数,使前面各数顺序向后移m个位置,最后m个数变成最前面m个数c语言
```c
#include <stdio.h>
void moveElements(int arr[], int n, int m) {
int temp[m];
for (int i = 0; i < m; i++) {
temp[i] = arr[n - m + i];
}
for (int i = n - 1; i >= m; i--) {
arr[i] = arr[i - m];
}
for (int i = 0; i < m; i++) {
arr[i] = temp[i];
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int m = 3;
moveElements(arr, n, m);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
C语言写有n个整数,使前面各数顺序向后移m个位置,最后m个数变成前面m个数
这个问题可以通过以下步骤解决:
1. 将前面n-m个数逆序。
2. 将后面m个数逆序。
3. 将全部n个数逆序。
代码示例:
void reverse(int arr[], int start, int end){
while(start < end){
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void shift(int arr[], int n, int m){
reverse(arr, 0, n-m-1);
reverse(arr, n-m, n-1);
reverse(arr, 0, n-1);
}
int main(){
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int m = 2;
shift(arr, n, m);
for(int i = 0; i < n; i++){
cout << arr[i] << " ";
}
return 0;
}
输出结果为:4 5 1 2 3
希望能解决您的问题。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)