c++ - 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";
}
我认为其中大部分可能是错误的,所以请随意丢弃。
任何帮助是极大的赞赏。谢谢!
解决方案
您的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; });
推荐阅读
- c# - 如何让用户角色检查它是什么?
- python - 无法从 PySpark 写入文件(.csv、.parquet)
- rest - 内部错误 (500) 是否应该成为 Swagger API 文档的一部分?
- c# - 如果我按下键盘按钮,是否有*短代码*让球(玩家)跳跃?
- java - Future 和 Mono 之间的区别
- docker - 如何在阻止整个互联网的同时让 docker 容器公开端口?
- xamarin - 使用 Xamarin.UITest 测试我的 Xamarin.Forms iOS 应用程序:第一个测试总是失败
- sql-server - 如何将 if then 语句与 select 语句嵌套,包括其他 if then 语句?
- javascript - 自动选择下一个输入字段并返回
- accessibility - 可访问性:编码时站起来的编码器