繁体   English   中英

如何在数组中查找一个值并将其复制到 C 语言中的另一个值?

[英]How to find a value in array and copy it to another one in C language?

我编写了一个代码,从标准输入中读取了 3 个卡车 ID,并将它们存储在一个数组中。

id 数组是名为 tTruckList 的结构的一部分,我在其中存储 id 和我们拥有的卡车数量。 所以,如果我们有一个 id,那么我们就有一辆卡车。

因此,在这之后,我们同时拥有ab arrays,每个数组都填充了 3 个整数,并更新了卡车的数量。

Then I want to compare each position of the array a.id to each position of the array b.id and if the value is the same, then copy it in a third array c.id within the c truck list.

为此,我在另一个 for 循环中编写了 for 循环。 所以我可以将拳头a.id[0]与数组b.id的每个 position 进行比较,如果值相同,我将其复制到c.id[i]中。 如果我没有找到相同的值,那么我 go 到 a.id[1] 执行相同的步骤。

但是,这最后一步不适用于我当前的代码,我不知道错误在哪里。 你可以帮帮我吗?

这是我的代码谢谢:

#include <stdio.h>
#define MAX 3

typedef struct {
    int id[MAX];
    int numTrucks;
} tTruckList;
    
int main (int argc, char** argv) {
    
    tTruckList a, b, c;
    a.numTrucks = 0;
    int i;
    int pos;
    int aux;
    int aux2;
    
    for(i=0; i<MAX; i++){
        printf("id of truck a >>\n");
        scanf("%d", &a.id[i]);
        a.numTrucks = a.numTrucks + 1;
    }
    
    for(i=0; i<MAX; i++){
        printf("id of truck b >>\n");
        scanf("%d", &b.id[i]);
        b.numTrucks = b.numTrucks +1;
    }
    
    c.numTrucks = 0;
    
    for(i=0; i<MAX; i++){
        aux = a.id[i];
        pos=0;
        for(i=0; i<MAX; i++){
            aux2 = b.id[i];
            if(aux == aux2){
                c.id[i-pos]= aux;
                c.numTrucks= c.numTrucks +1;
            } else {
                pos = pos + 1;
            }
        }
    }
    
    printf("first id c: %d\n", c.id[0]);
    printf("second id c: %d\n", c.id[1]);
    printf("third id c: %d\n", c.id[2]);
    printf("number of trucks c: %d\n", c.numTrucks);
    
return 0;
}

您在外循环和内循环中使用了相同的变量i ,因此外循环将只运行一次,因为运行内循环后i将是MAX

为循环使用不同的变量来避免这种情况。

还要注意不要打印c.id的未初始化元素。

另一点是您的使用pos是错误的。 在最坏的情况下,您必须查看所有元素以确定是否存在具有相同值的元素,因此认为只有一个元素没有具有相同值的元素是错误的。

    c.numTrucks = 0;
    /* initialize c.id not to print unintialized variables */
    for(i=0; i<MAX; i++){
        c.id[i]=0;
    }
    
    for(i=0; i<MAX; i++){
        aux = a.id[i];
        for(pos=0; pos<MAX; pos++){ /* use different variable than the outer loop in the inner loop */
            aux2 = b.id[pos];
            if(aux == aux2){
                c.id[c.numTrucks]= aux;
                c.numTrucks= c.numTrucks +1;
                break; /* an element with the same value is found, so no additional iteration is required */
            }
            /* delete else part not to take extra actions seeing only one element */
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM