用c语言写一下程序有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面m个数。 输入提示:"共有多少个数?" 输入格式:"%d" 输入提示:"后移多少个?" 输入格式:"%d" 输出提示:"请以,号为间隔输入%d个数。\n" 输出格式:"%d," 输出提示:"移动后顺序为:\n" 输出格式:"%d," 程序的运行示例如下: 共有多少个数?5 后移多少个?2 请以,号为间隔输入5个数。 1,2,3,4,5 移动后顺序为: 4,5,1,2,3
时间: 2023-07-19 13:06:54 浏览: 49
以下是用C语言编写的程序:
```c
#include <stdio.h>
int main() {
int n, m, i, j;
printf("共有多少个数?");
scanf("%d", &n);
printf("后移多少个?");
scanf("%d", &m);
int a[n];
printf("请以,号为间隔输入%d个数。\n", n);
for (i = 0; i < n; i++) {
scanf("%d,", &a[i]);
}
for (i = 0; i < m; i++) {
int temp = a[n - 1];
for (j = n - 1; j > 0; j--) {
a[j] = a[j - 1];
}
a[0] = temp;
}
printf("移动后顺序为:\n");
for (i = 0; i < n; i++) {
printf("%d,", a[i]);
}
printf("\n");
return 0;
}
```
程序运行结果:
```
共有多少个数?5
后移多少个?2
请以,号为间隔输入5个数。
1,2,3,4,5,
移动后顺序为:
4,5,1,2,3,
```
相关问题
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
希望能解决您的问题。
有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;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)