简体   繁体   English

比较两个不同数组中的值是否相等

[英]Comparing values in two different arrays for equality

I'm trying to compare two different arrays for equality between all values, except the one in the same position in the other array: for example array1[0]==array2[1] but not array1[0]==array2[0] I'm having a little bit of trouble and know there must be an easier way than what I'm doing which is this: This is in c by the way我正在尝试比较两个不同数组的所有值之间的相等性,除了另一个数组中相同位置的数组:例如 array1[0]==array2[1] 但不是 array1[0]==array2[0 ] 我遇到了一点麻烦,我知道一定有比我正在做的更简单的方法,这是:顺便说一下,这是在 c 中

for(int r=1; r<4;4++){
    if(choicearray[r]==comparray[r+1]||choicearray[r]==comparray[r-1] || choicearray[r]==comparray[r+2]|| choicearray[r]==comparray[r-2] || choicearray[r]==comparray[r-3] || choicearray[r]==comparray[r+3]){
    printf("w "); 
         e++;
   }
  } 

Both arrays contain 4 characters两个数组都包含 4 个字符

First of all remember that array are indexed starting from 0 (in your case 0 to 3).首先请记住,数组的索引从 0 开始(在您的情况下为 0 到 3)。

You have to loop throught the first array then loop through the second array.您必须遍历第一个数组,然后遍历第二个数组。

int n=4;
for(int r=0; r<n; r++){
    for(int q=0; q<n; q++){
        if(arrayA[r]==arrayB[q] && q!=r)
             printf("w ");
    }
}

The condition q!=r check that only different indexes are compared.条件q!=r检查是否只比较不同的索引。

For starters, you can try to use two loops, each to control iteration of one array like so:对于初学者,您可以尝试使用两个循环,每个循环都控制一个数组的迭代,如下所示:

for (int r=0; r<4;r++){
    for (int s=0; s<4;s++){
        if (s!=r){
            //do your comparing
        }
    } 
}

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

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