在计算机等级考试二级C语言程序设计试题中,按要求对数组元素进行移动处理是一个重要的考点,有关数组元素移动的试题在历年考试试卷的程序填空题和程序设计题中经常出现。
一.例题讲解
例1 编写函数fun,它的功能是:逆置数组元素中的值。
例如,若a所指数组中的数据依次为:1、2、3、4、5、6、7、8、9,则逆置后依次为:9、8、7、6、5、4、3、2、1。
#include <stdio.h>
void fun(int a[], int n)
{
}
int main()
{
int b[9]={1,2,3,4,5,6,7,8,9}, i;
printf("\nThe original data :\n");
for (i=0; i<9; i++)
printf("%4d ", b[i]);
printf("\n");
fun(b, 9);
printf("\nThe data after invert :\n");
for (i=0; i<9; i++)
printf("%4d ", b[i]);
printf("\n");
}
解析1:若数组中有n个元素,则分别将第1个元素(a[0])和第n个元素(a[n-1])对换,第2个元素(a[1])和第n-1个元素(a[n-2])对换,……。因此,逆置操作可写成一个循环,循环次数为数组元素个数的一半。当n为偶数,“一半”恰好是数组长度的二分之一;若n是奇数,“一半”是小于n/2的最大整数,这时取大于n/2的最小整数的位置上的元素,恰是数组中间位置的元素,不需要逆置。描述为:
for (i=0; i<n/2; i++)
{
// 将a[i] 和 a[n-1-i] 互换;
}
编写的函数fun如下:
void fun(int a[], int n)
{
int i,t;
for (i=0; i< n/2; i++)
{
t=a[i];
a[i] = a[n-1- i];
a[n-1-i] = t;
}
}
解析2:数组的逆置还可以采用如下的方法完成。
设置两个变量low和bottom分别指向数组的首尾。逆置操作过程如下:
1)将low指向的内容和bottom指向的内容相交换;
2)修改变量top和bottom,使top后移(top++),bottom前移(bottom--);
3)重复1)、2)操作,直到low>=bottom为止。
编写的函数fun如下:
void fun(int a[], int n)
{
int temp,top,bottom;
top=0;
bottom=n-1;
while(top<bottom)
{
temp=a[top];
a[top]=a[bottom];
a[bottom]=temp;
top++;
bottom--;
}
}
解析3:数组的逆置还可以采用递归的方法完成。
递归终止条件为:当n<2时,数组中的元素不足2个,无需处理直接返回。
递归方式为:当n>=2时,将数组a的n个元素进行逆置可以看成将首尾元素(a[0]和a[n-1])交换后,再将中间的n-2个元素逆置(递归调用fun(a+1,n-2)完成)。
编写的函数fun如下:
void fun(int a[], int n)
{
int t;
if (n<2) return ;
t=a[0]; a[0]=a[n-1]; a[n-1]=t;
fun(a+1,n-2);
}
例2 编写函数fun,它的功能是:计算形参x所指数组中N个数的平均值(规定所有数均为非负数),将所指数组中大于平均值的数据移至数组的前部,小于等于平均值的数据移至数组的后部,平均值作为函数值返回,在主函数中输出平均值和移动后的数据。
例如,有10个非负数:41 17 34 0 19 24 28 8 12 14,平均值为:19.700000
移动后的输出为:41 34 24 28 17 0 19 8 12 14。
#include <stdlib.h>
#include <stdio.h>
#define N 10
double fun(double *x)
{
}
int main()
{
int i;