使用数组消除重复

时间:2014-11-17 23:30:18

标签: c++ arrays

我无法理解这个问题。它要求从用户读取20个值,验证它们在10到100之间。如果数据有效,则仅在数据不重复时将其存储在数组中。经过20个值后,仅显示唯一值。我不知道为什么,但在我的代码中它存储每个值,无论它是否重复。我感谢任何帮助!

#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;
}

1 个答案:

答案 0 :(得分:0)

    if(duplicate[i] == numberEntered)
    {
        cout << "This number was already entered " << endl;
        dup = true;
        break;
    }

您正在检查duplicate[i],而不是针对索引j,这是检查重复项的循环,因此您的代码永远不会看到重复。