首页 > 解决方案 > C ++:如何查看数组中的元素是否超过某个值?

问题描述

C++ 新手,所以我提前为我的无能道歉。

我需要在函数 Main 之外编写一个函数来检查数组的元素(由用户输入)以查看它们是否超过 10。如果是,我需要打印该数量的元素以及一个列表元素本身。如果不是,我需要显示一条消息,说明没有。

我已经尝试了各种事情,但这是我不断回来的事情。你能帮忙吗?

void print_over_ten(const int list[], int length)
    //list[] contains user entered elements
    //length contains the length of the array, list[]
{
    int index=0;   //counter
    int amount;  //number of elements over 10
    int number_over_ten;    //variable for numbers over ten

    cout << "\nThese numbers are over ten: ";

    if (index > 10 && index <= length)
    {
        number_over_ten = index-1;
        cout << number_over_ten << " ";
        index++;
    }
    else
        cout << "\nThere are no numbers over 10.\n";

    amount = index;

    cout << "There are " << amount << " numbers over 10.\n";    
}

我认为其中大部分可能是错误的,所以请随意丢弃。

任何帮助是极大的赞赏。谢谢!

标签: c++arraysfunction

解决方案


您的if条件大部分是正确的,但是您需要在使用循环遍历数组时进行检查:

for (int i = 0; i < length; ++i)
{
  if (list[i] > 10)
    ++index;
}

if (index > 10)
    cout << "There are " << index << " numbers over 10.\n";    
else
    cout << "\nThere are no numbers over 10.\n";

关于命名的小提示:变量index没有描述它的作用。您可能应该counter按照您在评论中所写的那样调用它,或者amount像您稍后将其分配给具有该名称的变量那样调用它。


比循环更好的是使用这样的算法:

int amount = std::count_if(list, list + length, [](int i) { return i > 10; });

推荐阅读