簡體   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