编写函数 int com(int *a,int *b,int *c),实现将a和b两个已按升序排列的数组合并。。。怎么写这个程序?

⑴ 编写函数 int com(int *a,int *b,int *c),实现将a和b两个已按升序排列的数组(所有数组元素的值非0)合并成一个升序数组c,合并后的数组中不包含两个数组中相同的数,并将两个数组中相同数的个数作为com函数的返回值。
⑵ 编写main函数,声明三个整型数组,并对其中的两个数组用给出的测试数据初始化(各数组长度利用宏定义规定);调用函数com实现数组的合并,且不包含两个数组中相同的数,合并后存入第三个数组中;将合并后的数组及两个数组中相同的数的个数输出。
【测试数据】
数组a:3 6 7 18 23 33 35 43 48 78
数组b:2 7 13 21 33 37 48 50 58 67
【运行结果】
2 3 6 13 18 21 23 35 37 43 50 58 67 78
count=3

#include<stdio.h>
#define N 10
#define M 10
int com(int *a, int *b, int *c)
{
int i = 0, j = 0, t = 0, res = 0;
while (i < N && j < M)
{
if (a[i] < b[j]) c[t++] = a[i++];
else if (a[i] > b[j]) c[t++] = b[j++];
else 
{
c[t++] = a[i++];
j++, res++;
}
}
while (i < N) c[t++] = a[i++];
while (j < M) c[t++] = b[j++];
return res;
}

int main()
{
int a[] = { 3, 6, 7, 18, 23, 33, 35, 43, 48, 78 };
int b[] = { 2, 7, 13, 21, 33, 37, 48, 50, 58, 67 };
int c[N + M];
int res = com(a, b, c);
for (int i = 0; i < N + M - res; i++)
printf("%d ", c[i]);
printf("\ncount=%d\n", res);
return 0;
}

追问

谢谢,题目说还要把相同的数删掉,这个怎么办呢

追答#include<stdio.h>
#define N 10
#define M 10
int com(int *a, int *b, int *c)
{
int i = 0, j = 0, t = 0, res = 0;
while (i < N && j < M)
{
if (a[i] < b[j]) c[t++] = a[i++];
else if (a[i] > b[j]) c[t++] = b[j++];
else i++, j++, res++;
}
while (i < N) c[t++] = a[i++];
while (j < M) c[t++] = b[j++];
return res;
}

int main()
{
int a[] = { 3, 6, 7, 18, 23, 33, 35, 43, 48, 78 };
int b[] = { 2, 7, 13, 21, 33, 37, 48, 50, 58, 67 };
int c[N + M];
int res = com(a, b, c);
for (int i = 0; i < N + M - res - res; i++)
printf("%d ", c[i]);
printf("\ncount=%d\n", res);
return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-06-06
一、编写函数int com(int *a,int *b,int *c):
int com(int *a,int *b,int *c)
{
int i, j, k, count;
for(i=j=k=count=0;*(a+i) ||*(b+j) ;)
if(*(a+i) ==*(b+j))
{
count++;
i++;
j++;
}
else
{
if(*(a+i) ==0)*(c+k++)=*(b+j++);
else if(*(b+j) ==0)*(c+k++)=*(a+i++);
else *(c+k++)=*(a+i) <*(b+j)?*(a+i++):*(b+j++);
}
return count;
}
二、编写main函数
#define N 100
main()
{
int a[N]={3, 6 ,7 ,18 ,23 ,33 ,35 ,43, 48 ,78};
int b[N]={2 ,7 ,13, 21, 33, 37 ,48, 50 ,58 ,67};
int c[N]={0};
int count,i;
count=com(a, b, c) ;
printf("合并后的数组是:\n");
for(i=0;*(c+i) ;i++)printf("%3d",*(c+i)) ;
printf("\ncount=%3d\n",count) ;
}
有什么问题请留言。本回答被提问者采纳
相似回答