在数组

时间:2016-11-24 00:28:43

标签: c++ arrays

我正在制作一个读取数字数组的程序,然后只显示重复的数字。但是,我的代码行为奇怪,并打印出错误的输出(最后附加的输出)。到目前为止,这是我的代码:

#include <iostream>
using namespace std;
const int MAX_NUMBER_ELEMENTS = 20;

void fillArray (int a[], int size, int& numberUsed);
void deleteRepeats (const int a[], int numberUsed, int n);

int main()
{
    int array [MAX_NUMBER_ELEMENTS], numberUsed;

    cout << "This program reads in an array and scans for duplicate    elements. " << endl;
    cout << "Enter the array: \n";

    fillArray(array, MAX_NUMBER_ELEMENTS, numberUsed);
    deleteRepeats(array, numberUsed, 20);
}

void deleteRepeats (const int array[], int numberUsed, int n)
{
    int i, j;

    for (i = 0; i < n; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (array[i] == array[j])
                cout << "The duplicate " << array[i] << " was found. ";
        }
    }
}

void fillArray (int a[], int size, int& numberUsed)
{
    cout << "Enter up to " << size << " nonnegative whole numbers.\n"
         << "Mark the end of thae list with a negative number.\n";
    int next, index = 0;
    cin >> next;
    while ((next >= 0) && (index < size))
    {
        a[index] = next;
        index++;
        cin >> next;
    }

    numberUsed = index;
}

我的意见:

This program reads in an array and scans for duplicate elements. 
Enter the array: 
Enter up to 20 nonnegative whole numbers.
Mark the end of the list with a negative number.
1 1 3 5 -1

我的输出:

找到了副本1。找到了副本1。找到了副本1。找到了副本1。找到了副本1。找到了副本1。找到了副本1。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到了副本1。找到了副本1。找到了副本1。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到重复的0。找到了重复的0。

如您所见,输出未显示重复的数字。我认为它与循环有关,虽然我不知道如何调试它。任何人都可以告诉我为什么代码在读入的数字数组中显示重复的元素?任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

你的循环运行到数组的最大结尾(所以到20),你的数组似乎用零初始化,所以你的输入转换为

1 1 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

每0个报告背后都是零 - &gt;这就是您看到的输出,您的循环必须转到numberUsed而不是MAX_NUMBER_ELEMENTS ...

这里有一个可能的纠正(未经测试,但想法应该清楚):

void deleteRepeats (const int array[], int numberUsed, int n)
{
    int i, j;

    for (i = 0; i < std::min(numberUsed, n); i++)
    {
        for (j = i + 1; j < std::min(numberUsed, n); j++)
        {
            if (array[i] == array[j])
                cout << "The duplicate " << array[i] << " was found. ";
        }
    }
}

附录:只使用(i,j) < numberUsed是危险的,因为你可能会超出未初始化的记忆范围