请编写函数fun(),该函数的功能是:移动一维数组中的内容,若数组中有n个整数,要求把下标从p到n-1(p≤n-1)的数组元素平移到数组的前面。 例如,一维数组中的原始内容为1,2,3,4,5,6,7, 8,9,10,11,12,13,14,15,p

admin2009-02-15  23

问题 请编写函数fun(),该函数的功能是:移动一维数组中的内容,若数组中有n个整数,要求把下标从p到n-1(p≤n-1)的数组元素平移到数组的前面。
   例如,一维数组中的原始内容为1,2,3,4,5,6,7, 8,9,10,11,12,13,14,15,p的值为6。移动后,一维数组中的内容应为7,8,9,10,  11,12,13,14,15,1, 2,  3,  4,  5,  6。
   注意:部分源程序给出如下。
   请勿改动主函数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);
   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);   
   printf("\n\n");
   }

选项

答案void fun(int *w, int p, int n) { int i.j,t; for(i=p;i<=n-1;i++) /*循环右移n-p次*/ {t=w[n-11; for(j=n-2;j>=0;j--) /*实现循环右移*/ w[j+1]=w[j]; w[0]=t; }

解析 本题采用“循环右移”的算法。和我们在前面分析的稍有不同的是,—个是整型数组,—个是字符型数组。
转载请注明原文地址:https://kaotiyun.com/show/OTID777K
0

相关试题推荐
最新回复(0)