问答题
1. 请编写函数fun,其功能是:移动一维数组中的内容,若数组中有n个整数,要求把下标从0~p(含p,p小于等于n-1)的数组元素平移到数组的最后。
例如,一维数组中的原始内容为:1、2、3、4、5、6、7、8、9、10;p的值为3。移动后,一维数组中的内容应为:5、6、7、8、9、10、1、2、3、4。
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的内容,仅在函数fun的花括号中填入你编写的若干语句。
试题程序:
#include<stdio.h>
#define N 80
void fun(int *w, int p, int n)
{
}
main()
{ int a[N]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int i,p,n=15;
printf("The original data:\n");
for(i=0; i<n; i++)
printf("%3d",a[i]);
printf("\n\nEnter p:");
scanf("%d",&p);
fun(a,p,n);
printf("\nThe data after moving:\n");
for(i=0; i<n; i++)
printf("%3d",a[i]);
printf("\n\n");
}
【正确答案】void fun(int *w, int p, int n)
{ int x,j,ch;
for(x=0; x<=p;x++)
{ ch=w[0];
for(j=1;j<n;j++) /*通过for循环语句,将p+1到n-1(含n-1)之间的数组元素依次向前移动p+1个存储单元*/
{
w[j-1] =w[j];
}
w[n-1]=ch; /*将0到p个数组元素逐一赋给数组w[n-1] */
}
}
【答案解析】
本题要求把下标从0~p(含p,p小于等于n-1)的数组元素平移到数组的最后,可以根据输入的p值,通过for循环语句,将p+1~n-1(含n-1)之间的数组元素依次向前移动p+1个存储单元,即w[j-1]=w[j];,同时将0~p个数组元素逐一赋给数组w[n-1],也就是通过语句w[n-1]=ch;来实现此操作的。