【问题标题】:C++ Having an issue with filling an arrayC++ 在填充数组时遇到问题
【发布时间】:2020-02-07 01:44:37
【问题描述】:

我的 C++ 代码 出现问题,涉及从用户接收输入并根据该输入填充数组。对于我的 function fillArray(),我需要一种方法来读取一行中的所有输入,并用这些输入填充一个数组,直到用户最后输入 -1,不是正整数,或超过 20 个元素的阈值。

例如,如果我输入 1 2 3 4 5 6 -1 在一行上,我希望 displayArray() 函数输出 1 2 3 4 5 6,或者如果我写 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21,我希望 displayArray() 输出 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

似乎每当我最后输入 -1 时, displayArray() 输出类似 1 2 3 4 5 6 94837 或任意大的数字。如果有人可以帮助我解决这个问题,我将不胜感激,这是我的代码:

#include <iostream>
using namespace std;

const int CAPACITY = 20;

void displayArray(int array[], int numElements)
{
    for (int i = 0; i < numElements; i++)
        cout << array[i] << " ";
    cout << endl;
}

void fillArray(int array[], int& numElements)
{
    int arrayPosition = 0;
    int testArrayPosition = 0;
    int testArray[CAPACITY];
    bool continueReading = true;

    cout << "Enter a list of up to 20 integers or -1 to end the list";
    do
    {
        cin >> valueEntered;

        if (valueEntered == -1)
        {
          continueReading = false;
        } else if (valueEntered != -1) {
            array[arrayPosition] = valueEntered;
            arrayPosition++;
        }
    } while ((continueReading==true) || (arrayPosition >= CAPACITY));

    numElements = (arrayPosition+1);
}

int main()
{
    int array[CAPACITY];
    int numArrayElements = 0;

    fillArray(array, numArrayElements);
    displayArray(array, numArrayElements);

    cout << "NumArrayElements: " << numArrayElements << endl;
}

【问题讨论】:

  • 请提供minimal reproducible example。您发布的代码无法编译。
  • 您想在 do while 循环结束时将条件更改为while ((continueReading &amp;&amp; arrayPosition &lt; CAPACITY),同时numElements 应设置为arrayPosition,而不是arrayPosition + 1

标签: c++ arrays function logic


【解决方案1】:

您发布的代码无法编译。您在多个地方引用了变量valueEntered,但从未声明过它。

此外,以下构造没有意义:

if (valueEntered == -1)
{
    [...]
}
else if (valueEntered != -1)
{
[...]

由于第二个 if 语句的条件表达式与第一个语句的条件表达式完全相反,因此第二个 if 语句是多余的,可以去掉,像这样:

if (valueEntered == -1)
{
    [...]
}
else
{
[...]

但是,由于您在问题中指出,除正整数(不仅仅是 -1)之外的任何其他内容都应该导致您的程序结束,您需要将程序的该部分更改为以下内容:

if (valueEntered <= 0)
{
    continueReading = false;
}
else
{
    array[arrayPosition] = valueEntered;
    arrayPosition++;
}

另外,正如其他人在 cmets 部分所述,行

while ((continueReading==true) || (arrayPosition &gt;= CAPACITY));

应该改为

while ( continueReading &amp;&amp; arrayPosition &lt; CAPACITY )

和线

numElements = (arrayPosition+1);

应该改为

numElements = arrayPosition;

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 2019-11-19
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2020-01-04
    • 1970-01-01
    相关资源
    最近更新 更多