【问题标题】:How to find a value in array and copy it to another one in C language?如何在 C 语言中找到数组中的一个值并将其复制到另一个数组中?
【发布时间】:2021-05-14 12:50:00
【问题描述】:

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

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

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

然后我想将数组 a.id 的每个位置与数组 b.id 的每个位置进行比较,如果值相同,则复制它在 c 卡车列表中的第三个数组 c.id 中。

为此,我在另一个 for 循环中编写了 for 循环。所以我可以将拳头 a.id[0] 与数组 b.id 的每个位置进行比较,如果值相同,我将其复制到 c 中。 id[i]。如果我没有找到相同的值,那么我会去 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;
}

【问题讨论】:

    标签: arrays c for-loop tuples


    【解决方案1】:

    您在外循环和内循环中都使用了相同的变量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 */
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多