如何在此代码中创建一个输出数组中0的数量的函数?

时间:2015-09-01 16:08:50

标签: c++ integer

const int DECLARED_SIZE = 20;

void fillArray(int a[], int size, int& numberUsed) {
        cout << "Enter up to " << size << " nonnegative whole numbers.\n"
        << "Mark the end of the 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;
}

int search(const int a[], int numberUsed, int target)
{
    int index = 0;
    bool found = false;
    while ((!found) && (index < numberUsed))
        if (target == a[index])
            found = true;
        else
            index++;

    if (found)
        return index;
    else
        return -1;
}

由于某种原因,它总是输出0。

int findZero(const int a[], int target, int numberUsed, int zeroes)
    {
        for (int index = 0; index < numberUsed; index++)
        {
            if (target == a[index])
                zeroes++;
        }
        return zeroes;
    }

这是主要代码。

int main()
    {
    int arr[DECLARED_SIZE], listSize, target;

看起来帖子主要是代码 请添加更多详细信息

fillArray(arr, DECLARED_SIZE, listSize);

    char ans;
    int result;
    int zeroes;
    int numberUsed;
    do
    { 
        cout << "Enter a number to search for: ";
        cin >> target;
        int numberOfZeroes = findZero(arr, target, zeroes, numberUsed);
        cout << "The amount of zero = " << zeroes << endl;

代码还有更多,但我只包含了我需要输出数组中0的数量的部分。

1 个答案:

答案 0 :(得分:0)

数组中的元素数(readed,而不是数组的最大大小)

为什么它没有正确计算?那么你已经切换了参数...

    int main()
    {
        int arr[DECLARED_SIZE], listSize;

        fillArray(arr, DECLARED_SIZE, listSize);

        int target;
        do {
            cout << "Enter a number to search for: ";
            target = -1; // if you give wrong input to cin, it will end (at least)
            cin >> target;
            int numberOfZeroes = findZero(arr, target, listSize, 0);
            cout << "The amount of number = " << numberOfZeroes << endl;
        } while (target >= 0);
        return 0;
    }

为什么零通过呢?如果需要局部变量,请将其创建为int zeroes = 0;那个= 0非常重要!