c语言初学者 编写一个程序 把非重复的数据复制到目标群组
例子 :
如果含有 3, 1, 4, 1, 5, 9
那么将3, 1, 4, 5, 9复制到目标群组
必须含有
int remove_duplicates(int length, int source[length], int destination[length]);
不能使用printf getchar 还有 scanf
想问下怎么写
参考代码如下:
int remove_duplicates(int length, int source[length], int destination[])
{
int i,j,k=0;
for(i=0;i<length;i++){
int flag = 1;
for(j=0;j<=k;j++){
if(source[i]==destination[j]){
flag=0;
break;
}
}
if(flag)
destination[k++]=source[i];
}
return k;
}
#include <stdio.h>
int remove_duplicates(int length, int source[], int destination[])
{
int i, j = 0, k, found;
for (i = 0; i < length; i++)
{
found = 0;
for (k = 0; k < j; k++)
{
if (destination[k] == source[i])
{
found = 1;
break;
}
}
if (!found)
destination[j++] = source[i];
}
return j;
}
int main()
{
int source[6] = {3, 1, 4, 1, 5, 9}, destination[6], n;
n = remove_duplicates(6, source, destination);
for (int i = 0; i < n; i++)
printf("%d ", destination[i]);
return 0;
}
$ gcc -Wall main.c
$ ./a.out
3 1 4 5 9
遍历源数组,如果目标数组中不包含该元素则把该元素放入目标数组即可。