C++ 使用阵列消除重复
我很难理解这个问题。它要求从用户处读入20个值,验证它们是否在10到100之间。如果数据有效,则仅当数据不重复时才将其存储在数组中。浏览完20个值后,只显示唯一的值。我不知道为什么,但在我的代码中,它存储每个值,不管它是否重复。谢谢你的帮助C++ 使用阵列消除重复,c++,arrays,C++,Arrays,我很难理解这个问题。它要求从用户处读入20个值,验证它们是否在10到100之间。如果数据有效,则仅当数据不重复时才将其存储在数组中。浏览完20个值后,只显示唯一的值。我不知道为什么,但在我的代码中,它存储每个值,不管它是否重复。谢谢你的帮助 #include <iostream> using namespace std; int main() { int duplicate[20]; int numberEntered; int currentIndex
#include <iostream>
using namespace std;
int main()
{
int duplicate[20];
int numberEntered;
int currentIndex = 0;
bool dup = false;
for (int i = 0; i < 20; i++) duplicate[i] = 0; //initializes all indices to 0
cout << "Enter 20 numbers " << endl;
for (int i = 0; i <= 20; i++)
{
cout << "Enter Number " << endl;
cin >> numberEntered;
if((numberEntered > 10) && (numberEntered < 100) )
{
for (int j = 0; j < currentIndex; j++)
{
if(duplicate[i] == numberEntered)
{
cout << "This number was already entered " << endl;
dup = true;
break;
}
}
if(dup==false)
{
duplicate[currentIndex] = numberEntered;
currentIndex++;
}
}
else
{
cout << "Invalid Number, must be between 10 and 100 " << endl;
i -- ;
}
}
for (int i = 0; i < currentIndex; i++)
{
cout << duplicate[i] << endl;
}
return 0;
}
在
您检查的是重复[i],而不是索引j,索引j是检查重复项的循环,因此您的代码永远不会看到重复项。谢谢!我修好了。但现在,每当你放入一个副本,它不会存储任何后续的数字。例如,当我输入12时,它存储12。13,商店13。14商店14。现在,再次输入12,它不会存储它。现在,尝试输入56,但不存储它。它只是停止…那是因为你没有将dup重置为false。为什么不使用调试器一步一步地检查代码呢。这会让你自然而然地发现这些逻辑错误。你会怎么做?调试语句中的代码?或者你可以使用实际的调试器,因为我从来没有使用过,我真的不知道它是如何工作的使用像std::find_if这样的算法。代码可以简单得多。
if(duplicate[i] == numberEntered)
{
cout << "This number was already entered " << endl;
dup = true;
break;
}