将数字与数字数组进行比较

Comparing a number with an array of numbers

本文关键字:数字 比较 数组      更新时间:2023-10-16

我想写一个代码,其中我必须将一个数字与数组的所有元素进行比较。该数字只能等于数组的一个元素,也可以不等于任何元素。我可以使用 for 循环中的 if 语句将数字与数组的每个元素进行比较。问题是当我想写"数字不等于数组的任何元素"时。下面显示的代码将执行 else 语句 99 或 100 次,但我只需要执行一次,在 number 与所有 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;
    }
}

这段代码应该是正确的:当它找到数组中一个等于你要找的数字的元素时,它会中断将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;

我认为这可能会提供您正在寻找的答案,使用计数器来确定它是否存在多次。 注意 - 我没有运行此代码!据我所知,考虑到稍微模棱两可的问题,它更具可扩展性,并且应该满足您是否需要查找出现一次、一次或多次出现的值的需求。

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;

您可以尝试 STL 提供的算法。std::find 算法可能是您正在寻找的。

这是因为您将"数字">与数组"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;
}