Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;数组元素比较_C++_Dev C++ - Fatal编程技术网

C++ C++;数组元素比较

C++ C++;数组元素比较,c++,dev-c++,C++,Dev C++,我想在两个数组中进行比较,我尝试了以下方法: #include <iostream> using namespace std; int main(){ int v1[10] = {1, 5, 77, 3, 4, 0, 2, 6, 8, 9}; int v2[10] = {20, 18, 2, 3, 4, 0, 1, 9, 6, 8}; int i,l,c=0,n=0; //comparision for(i=0; i<10; i++) { for(

我想在两个
数组中进行比较,我尝试了以下方法:

#include <iostream> 

using namespace std; 

int main(){ 
int v1[10] = {1, 5, 77, 3, 4, 0, 2, 6, 8, 9}; 
int v2[10] = {20, 18, 2, 3, 4, 0, 1, 9, 6, 8}; 
int i,l,c=0,n=0; 

//comparision
for(i=0; i<10; i++) 
{ 
    for(l=0;l<10;l++) 
    { 
        if ((v1[i] == v2[l]) && (c==0)) 
        { 
            cout << v1[i] << " e " << v2[l] << " are common" << endl; 
            c = 1; 
        } 
        else if((n==0) && (l==10)) 
        { 
            cout << v1[i] << " it s in only one array" << endl; 
            n = 1; 
        };
    } 
    c=0,n=0; 
} 

system("pause"); 
return 0; 
}
#包括
使用名称空间std;
int main(){
intv1[10]={1,5,77,3,4,0,2,6,8,9};
intv2[10]={20,18,2,3,4,0,1,9,6,8};
int i,l,c=0,n=0;
//比较

对于(i=0;i您的
l
永远不能为10,这是显示唯一元素的条件。循环将在9处停止

我建议您只使用一个变量来标记唯一性。例如:

bool found = false;
for(i = 0; i < 10; i++) 
{ 
    for(l = 0; l < 10; l++) 
    { 
        if ((v1[i] == v2[l])) 
        { 
            cout << v1[i] << " e " << v2[l] << " are common" << endl; 
            found = true; 
        } 
        else if(!found && l==9) 
        { 
            cout << v1[i] << " it s in only one array" << endl; 
        }
    } 
    found = false; 
}
boolfound=false;
对于(i=0;i<10;i++)
{ 
对于(l=0;l<10;l++)
{ 
如果((v1[i]==v2[l]))
{ 

请提供更多细节,以便任何人都能提供帮助。1)更详细地解释2)在发布前使用调试器,这样你就可以看到逻辑在运行,而且大多数时候你都会看到问题。请缩进。这段代码很糟糕,因此很难理解。3)缩进代码以便易于理解。@PaulB我在中编辑了缩进。我建议将
bool find=false;
a如果不是第一个循环体的开头,那么您不需要在底部重复它。@Barmar这是真的!进行了相应的编辑。非常感谢@Felix我用l=9尝试了您的解决方案,但我不理解一件事,或者我无法解释它,如果我想在2个数组中找到找到的元素,直到10个循环,为什么l=9?也许我错了从我的循环开始,我必须使用C++中的i@ AigaA500数组从零开始。所以第十元素是索引9的元素。如果找到相似的元素,我们就设置标志为true。因此,我们知道如果在每个元素之后发现“false”仍然是错误的,那么它就不匹配。它有用吗?@ Felix,一切都好,就在你的第一个席上。我在节目结束时得到的答案是“92只在一个数组中”,但我在数组中输入的数字是92,那么问题出在哪里?你和我一样吗?提前谢谢
for(int i = 0; i < 10; i++){
    bool found = false;
    for(int j = 0; j < 10; j++){ 
        if ((v1[i] == v2[j])){ 
            cout << v1[i] << " e " << v2[j] << " are common" << endl; 
            found = true; 
        }
    }
    if(!found){
        cout << v1[i] << " is in only one array" << endl; 
    }
}