簡體   English   中英

比較兩個數組並檢查條件

[英]comparing two arrays and checking a condition

我正在使用codeBlocks(C),我想比較兩個數組(有x個數字)。 每個數組由一些學生的成績(數字,整數)組成,每個數組代表一個班級。

我想對它們進行比較,看看是否有相同數量的學生和相同的成績。 例如

[75 58 86 75 98] 
[58 75 98 86 75] 

在實現目標的同時

[75 58 86 75 98] 
[58 86 98 86 75] 

不要因為第一堂課有75次,而第二堂課只有75次。

我知道如何比較它們,但我無法檢查它們是否達到目的,謝謝

for (int i = 0; i < x; i++) {
    for(int j=0; j < x; j++){
        if ( class1 [i] == class2[j]) continue;

    }
}

您應該首先對兩個數組進行排序。 完成此操作后,您可以在一個循環中比較它們,並從每個循環中檢索相同的數組索引。

您可以使用qsort函數對每個數組進行排序。

最好的方法可能是它們進行排序 ,以便並且僅當它們在每個位置具有相同的值時(並且顯然它們具有相同的長度,但是您甚至可以在排序之前進行檢查),才能滿足您的要求。

看起來像這樣(從鏈接的答案中大量復制了代碼)

int comp (const void * elem1, const void * elem2) 
{
    int f = *((int*)elem1);
    int s = *((int*)elem2);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}

然后在需要檢查時:

qsort (class1, sizeof(class1)/sizeof(*class1), sizeof(*class1), comp);
qsort (class2, sizeof(class2)/sizeof(*class2), sizeof(*class2), comp);

for (int i = 0; i < x; i++) {
        if ( class1 [i] != class2[i]) return false; 
}
return true;

暫無
暫無

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

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