将数字与数字数组进行比较
Comparing a number with an array of numbers
我想写一个代码,其中我必须将一个数字与数组的所有元素进行比较。该数字只能等于数组的一个元素,也可以不等于任何元素。我可以使用 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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++通过数字比较两个数字
- 如果相同的数字重复,如何比较流中的数字
- 使用三个数字比较器进行排序
- 如何实现通用比较?(用于数字和字符串)
- 数字之间的比较
- 如果堆栈在数字较低的地址增长,为什么指针比较会逆转这种情况?
- 如何将字符与数字进行比较?C++
- sort() 方法 c++ 中的比较器函数.为大量数字获得不同的解决方案
- 比较推送数据(100 万个数字)在 std::vector 中预先调整大小和没有
- 将数字与数字数组进行比较
- 在没有比较运算符的情况下查找 2 个数字之间的最小值
- 计数交换/比较合并排序算法的数字
- 比较二维数组中的数字时的无限循环
- C++ 比较 2 个不同列表中的值以使用 2 for 循环摆脱重复的数字。无法正确检测重复项
- c++ 输入一个数字来确定其他数字,然后比较它们
- 如何将计数器添加到气泡排序中以计数数字比较
- 两种数字比较方法中哪一种更有效
- 无法获得如果(数字== 1)比较工作
- 数字比较比字符串比较快