问题描述
我是C ++的初学者,我需要一个基本问题的帮助。我有一个数据集(数组),任务是计算满足给定条件的元素数量。
公司存储员工的年龄和工资。我们需要编写一个程序,告诉您L岁以上有多少人的工资低于M。
输入
标准输入(0≤N≤100),年龄限制(1≤L≤100)第一行的工人人数 薪金上限(1≤M≤2,000,000)且低于该上限为每行一个人的年龄 (1≤K≤100)和薪水(1≤F≤2,000)。
在标准输出的一行中,年龄在L以下且工资低于M的那些 必须写出工人人数。
#include <iostream>
using namespace std;
int main()
{
int N;
int K;
int L;
int F;
int M;
cin >> N >> K >> L >> F >> M;
int arr[N];
for (int i=0; i<N; ++i)
{
cin >> arr[i];
}
int DB=0;
for (int i=0; i<N; ++i)
{
for (int DB; K>L && F<M; DB=DB+1)
{
}
}
cout << DB << endl;
return 0;
}
我试图使用for循环解决问题。显而易见,代码中存在基本错误。您能帮我解决问题吗?上面的代码是一种好的方法还是有更好的解决方案?
谢谢您的帮助。
解决方法
这无疑是解决问题的一种创新方式! 一种更简单的方法是遍历每个元素,并检查它们是否匹配,如下所示:
#include <iostream>
using namespace std;
int main(){
int numWorkers,ageLimit,salaryLimit,matchCount=0;
cin >> numWorkers >> ageLimit >> salaryLimit;
for (int i = 0; i < numWorkers; i++){
int age,salary;
cin >> age >> salary;
if (age > ageLimit && salary < salaryLimit){
matchCount++;
}
}
cout << matchCount << endl;
return 0;
}
,
这是一种方法,请注意,这只是基于帖子评论的示例。
#include <iostream>
#include <vector>
#include <algorithm>
// you need a way to capture the information of age and salary
class Employee
{
public:
Employee(int age,int salary) : m_age(age),m_salary(salary)
{}
int Salary() const { return m_salary; }
int Age() const { return m_age; }
private:
int m_age{0};
int m_salary{0};
};
int main()
{
// an array of the employees with age and salary,avoid using native arrays
std::vector<Employee> employees{{21,10000},{22,12000},{54,54500},{62,60000},{32,32000}};
// some salary limit or use cin to read in it
auto salaryLimit = 33000;
// use count_if to count the number of employees under salary limit
auto nrOfEmployees = std::count_if(employees.begin(),employees.end(),[=](const Employee& e){return e.Salary() < salaryLimit;});
std::cout << nrOfEmployees << std::endl;
return 0;
}
如果您想尝试代码