将大于数组值的数字存储到另一个数组中

时间:2017-11-10 07:53:52

标签: c++ arrays list sorting

我是初学者C ++程序员,所以我为我的凌乱代码道歉。我有一个赋值,我需要创建一个函数来传递用户创建的列表/数组,以打印出大于10的所有整数和计数。当用户输入负数时,程序将结束并打印用户输入的任何内容(如果有的话)。到目前为止,我的部分解决方案包括:

void PrintGreaterThan(const int list[]) {
    int index, finalCount, greaterThan[MAX_SIZE];
    finalCount = 0;
    for (index = 0; index < MAX_SIZE; index++) {
        if (list[index] > 10) {
            greaterThan[index] = list[index];
            finalCount++;
        }

    }
    cout << "The list contains " << finalCount <<
        " non-negative integer(s) that are \ngreater than 10 as follows: " << 
    endl;
    for (int count = 0; count < finalCount; ++count) {
        cout << greaterThan[count] << " ";
    }
    cout << "\n\n\n";
}

我的程序能够接收用户输入,例如``1 2 3 4 5 -1,并且没有打印出来,这是正确的。如果我输入20 30 40 50 2 3 4 -1,该程序将仅显示10以上的数字并更正10以上的数字,这也是正确的。但是当我输入例如30 40 2 3 20 40时,程序将打印出30 40,然后输出错误值。我觉得我错过了一些东西......也许我错误地实施了这个?我想过如果数字是10并且在?之下,可能会跳过数组元素的方法?程序有不同的部分,这就是为什么我没有发布整个事情,以防万一有太多不必要的细节。谢谢。

1 个答案:

答案 0 :(得分:3)

问题是您使用的index作为listgreaterThan的索引。这意味着当数字不大于10时,您跳过greaterThan中的该索引,并且该元素未被初始化。当您打印结果时,即使填写了finalCount的较高元素,您也只能前往greaterThan

您应该为索引使用另一个变量greaterThan。您可以使用finalCount变量,因为它会根据您的需要增加。

    if (list[index] > 10) {
        greaterThan[finalCount] = list[index];
        finalCount++;
    }
相关问题