簡體   English   中英

如何比較和注冊復制的數組值

[英]How to compare and register array values which are replicated

我在解釋此練習的邏輯時遇到麻煩。

練習要求我在一個結構中注冊5個“品牌”,並且輸出結果必須顯示每個品牌重復了多少次(如果已注冊了多個)。

#include <stdio.h>
#include <stdlib.h>

#define C 5

typedef struct      
{
    int id;
    char brands[30];
} Something;


Something a[C];
int main() 
{
    int i=0, j=0;

    //input
    for(i=0;i<C;i++)
    {
        a[i].id = i;

        printf("BRAND: ");
        fflush(stdin);
        gets(a[i].brands);
    }

    for(i=0;i<C;i++)
    {
        for(j=0;j<C;j++)
        {
            if (strcmp(a[i].brands, a[j].brands)==0)
                // 
        }
    }
    return 0;
}

品牌輸入值不是恆定的,可以是任何值。

因此,我想通過搜索進行比較,比較是否有相等的品牌,並為每個品牌增加一個計數器。 (因為我不知道注冊表中會有多少個不同的品牌,所以這個計數器是我停留的地方)...

例如1
輸入項

Ford
Ferrari
Ford
Nissan
Nissan

輸出應如下所示:

Ford 2x
Ferrari 1x
Nissan 2x


例如2
輸入項

Ford
Ford
Ford
Ford
Nissan

輸出:

Ford 4x
Nissan 1x

有很多方法可以實現您想要的。 以下是一些指針,希望可以幫助您找到解決方案。

第一步是在您的結構中包含一個計數器。

typedef struct      
{
    int id;
    char brands[30];
    unsigned int count;
} Something;

將所有count字段初始化為0。如果count大於0,則brands字段僅包含有效字符串。由於a是全局變量,因此所有字段都會自動初始化為0,因此不需要額外的代碼。

然后,每次您讀取輸入內容時,代碼都會從頭開始搜索a 搜索邏輯將是

for each 'a' entry
    if (count field > 0)
        if (brand field is same as input)
            // Found a match
            increment count field
            break out of loop
        // else will check next entry by continuing the loop
    else
        // Reached end of valid entries. Hence no match.
        Create a new entry. Copy input into the brand field. 
        Set count field to 1.
        break out of loop

我特意展示了偽代碼,以保留C代碼作為練習。 但基本上,這個想法是(如我之前的評論中所述)在讀取每個輸入后搜索現有的有效條目(您不需要兩個單獨的數組)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM