m0_59696689 2021-07-06 21:17 采纳率: 70.6%
浏览 33
已采纳

c语言中关于集合的小问题(求解)

这个是我的代码,但是有问题,能不能帮忙改一改

#include<stdio.h>
int common_elements(int length, int source1[length], int source2[length], int destination[length]) {
    int i = 0;
    int e = 0;
    while (i < length) {
        int a_i = 0;
        while (a_i < length) {
            if (source1[i] == source2[a_i] && source2[a_i] != destination[e] && source1[i] != destination[e]) {
                destination[e] = source1[i];
                e++;
                a_i++;
            }
            a_i++;
        }
        i++;
    }
    return e;
}
int main(void){
    return 0;
}

图片绿色的那行是正确的形式,红色的是我写的错误的形式。

img

图片显示的那一行应该是有问题的,但我不知道怎么改。

img

  • 写回答

2条回答 默认 最新

  • qfl_sdu 2021-07-06 23:02
    关注

    代码修改如下:

    #include<stdio.h>
    #include <stdlib.h>
    int common_elements(int length, int source1[], int source2[], int destination[]) 
    {
        int i = 0;
        int e = 0;
        int* p = (int*)malloc(sizeof(int)*length);
        for (i=0;i<length;i++)
            p[i] = 0;
        i = 0;
        while (i < length) 
        {
            int a_i = 0;
            while (a_i < length) 
            {
                if (source1[i] == source2[a_i] && p[a_i]==0) 
                {
                    p[a_i] = 1;
                    destination[e] = source1[i];
                    e++;
                    a_i++;
                    break;
                }else
                    a_i++;
            }
            i++;
        }
        free(p);
        return e;
    }
    int main(void){
    
        int source1[]={1,4,1,5,9,2};
        int source2[] ={1,1,2,3,5,8};
    
        int source3[] ={9,2,3,4,5,6,7,8,1,9};
        int source4[] ={3,1,4,1,5,9,2,6,5,3};
    
        int s3[6]={0};
        int s4[10]={0};
        int i,res1,res2;
        res1 = common_elements(6,source1,source2,s3);
        for (i = 0;i<res1;i++)
            printf("%d ",s3[i]);
        
        printf("\n");
    
        res2 = common_elements(10,source3,source4,s4);
        for (i = 0;i<res2;i++)
            printf("%d ",s4[i]);
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么