我想编写一个代码,其中我必须将数字与数组的所有元素进行比较。该数字只能等于数组的一个元素或不等于任何元素。我可以使用for循环中的if语句将数字与数组的每个元素进行比较。问题是当我想写#34;数字不等于数组中的任何元素时。下面显示的代码将执行else语句99或100次,但我需要只执行一次,将数字与所有X [i]进行比较后找不到相同的数字。
for(int i = 0; i < 100; i++)
{
if(number == X[i])
{
cout << "number is equal to one of the numbers in array" << endl;
}
else
{
cout << "number is not equal to any number in the array" << endl;
}
}
答案 0 :(得分:4)
这段代码应该是正确的:当它找到一个与你要查找的数字相等的数组元素时,会打破将bool
变量转换为true的循环。因此,如果它为假(if(!check)
),则该数字不在数组中。
bool check = false;
for (int i = 0; i < 100; i++)
{
if(number == X[i])
{
cout<<"number is equal to one of the numbers in array"<<endl;
check = true;
break;
}
}
if (!check)
cout<<"number is not equal to any number in the array"<<endl;
答案 1 :(得分:1)
您可以尝试STL提供的算法。 std::find算法可能就是你要找的。 p>
答案 2 :(得分:1)
那是因为您要将“数字”与数组“X”中的每个数字进行比较,并且每次2个数字不时等于你打印那个陈述。
你想要的是更像这样的东西:
bool foundNumber = false;
for(int i=0;i<100;i++){
if(number==X[i]){
cout<<"number is equal to one of the numbers in array"<<endl;
foundNumber = true;
break; //The "break" command just exits out of the loop and if you already know it's equal, you can just exit the loop
}
}
//Now that we are out of the loop, we check the "foundNumber" variable
if(foundNumber==false){
//If "foundNumber" is false, then we can print out that we did not find the number
cout<<"number is not equal to any number in the array"<<endl;
}
答案 3 :(得分:1)
我认为这可能会提供您正在寻找的答案,使用计数器来查明它是否存在多次。注意 - 我没有运行此代码!据我所知,鉴于略微模棱两可的问题,它更具可扩展性,并且应满足您是否需要找到一次显示的值,仅一次的需求,或不止一次。
unsigned int count = 0;
for (int i = 0; i < 100; i++)
{
if(number == X[i])
{
count++;
}
}
if (count == 1) //Edit with == x, or > or < symbols to change frequency requirements
cout << "Number exists " << count << " time(s) in array"<<endl;
else
cout << "Number does not exist only once in array" << endl;