如何制作不允许重复值的C ++ int数组循环?

时间:2018-09-20 03:47:00

标签: c++ arrays loops input int

我需要一个循环,该循环将不断请求输入,直到数组中没有重复的值为止。当我运行我的代码时,它将识别出重复的内容,但是它将遍历我的代码的其余部分,并且不再要求再次输入。我已经尝试了许多不同的方法,因此非常感谢任何见识

cout << "Enter 10 integers with no repeated values: ";
for (x = 0; x < n; x++)
{
    cin >> d[x];
}

while (duplicateTest(d))
{
    for (x = 0; x < n; x++)
    {
        cin >> d[x];
    }
}



bool duplicateTest (int d[])
{
int i, j;
bool duplicate;
for (i = 0; i < 10; i++)
{
    for (j = i + 1; j < 10 + 1; j++)
    {
        if (d[i] == d[j])
        {
            cout << "Invalid entry, do not repeat values." << endl
                 << "Enter 10 integers with no repeated values: " << endl;  
            duplicate = true;
        }
        else 
            duplicate = false;

    }
}

return duplicate;

3 个答案:

答案 0 :(得分:0)

duplicateTest()中,设置duplicate = true后,您需要返回。考虑[0][1]相同。您将设置duplicate = true,然后比较[1][2],它们是不同的,因此duplicate将返回到false。找到重复项后,您就可以停止寻找-您不必担心有多少个重复项。

答案 1 :(得分:0)

一旦发现一个重复项,您的duplicateTest函数应被重写以返回true

bool duplicateTest(int (&d)[10]) {
    for (int i = 0; i < 10; ++ i)
        for (int j = i + 1; j < 10; j++)
            if (d[i] == d[j]) {
                std::cout << "Invalid entry, do not repeat values\n"
                             "Enter 10 integers with no repeated values:\n";
                return true;
            }
    return false;
}

目前,它会在发现重复项时将duplicate设置为true,但是在以后的迭代中,当某些{{1} } false对不是重复的

为了使您的代码能够编译,我需要做一些工作,下面是一个有效的示例:

d[i]

答案 2 :(得分:-1)

问题是您要覆盖plicateTest()中的重复标记。

    cout << "Enter 10 integers with no repeated values: ";
    for (x = 0; x < n; x++)
    {
        cin >> d[x];
    }

    while (duplicateTest(d))
    {
        cout << "Duplicate value found. Enter 10 integers with no repeated values: ";
        for (x = 0; x < n; x++)
        {
            cin >> d[x];
        }
    }



bool duplicateTest (int d[])
{
    int i, j;
    bool duplicate = false; //Better to initialize.
    for (i = 0; i < 10; i++)
    {
        for (j = i + 1; j < 10 + 1; j++)
        {
            if (d[i] == d[j])
            {
                cout << "Invalid entry, do not repeat values." << endl
                     << "Enter 10 integers with no repeated values: " << endl;  
                duplicate = true;
                break; //If you detect at least one duplicate, exit the loop.
            }
            else 
                duplicate = false;

        }
        if(duplicate) break; //Break the outerloop.
    }

    return duplicate;
}