Вопрос задан 22.06.2023 в 12:50. Предмет Информатика. Спрашивает Никифоров Дмитрий.

C++ Сделать на структурах На предприятии необходимо хранить данные о работниках: фамилию, имя,

отчество, дата рождения, должность, стаж. Вывести на экран данные о тех работников, которые на текущий момент времени достигли 37 лет и имеют стаж не менее 10 лет.
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Федюкевич Маргарита.
  • #include <iostream>
  • #include <utility>
  • #include <vector>
  • #include <list>
  • #include <ctime>
  • #include <string>
  • namespace business {
  •    using namespace std;
  •    struct Date {
  •        int day;
  •        int month;
  •        int year;
  •        Date() = default;
  •        Date(int _day, int _month, int _year) : day(_day), month(_month), year(_year) {}
  •        explicit Date(tm date) {
  •            day = date.tm_mday;
  •            month = date.tm_mon;
  •            year = date.tm_year;
  •        }
  •        ~Date() = default;
  •        Date operator- (Date& date) const {
  •            Date diff{};
  •            diff.year = year;
  •            diff.month = month;
  •            diff.day = day;
  •            diff.day -= date.day;
  •            if (diff.day <= 0) {
  •                diff.day = 31 - diff.day;
  •                diff.month -= 1;
  •            }
  •            diff.month -= date.month;
  •            if (diff.month <= 0) {
  •                diff.month = 12 - diff.month;
  •                diff.year -= 1;
  •            }
  •            diff.year -= date.year;
  •            return diff;
  •        }
  •    };
  •    struct Worker {
  •        string fio;
  •        Date birthday{};
  •        string job;
  •        int stage{};
  •        Worker() = default;
  •        Worker(string fio, Date birthday, string job, int stage){
  •            this->fio = move(fio);
  •            this->birthday = birthday;
  •            this->job = move(job);
  •            this->stage = stage;
  •        }
  •        ~Worker() = default;
  •    };
  •    struct Business {
  •    private:
  •        vector<Worker> workers;
  •    public:
  •        Business() = default;
  •        ~Business() = default;
  •        void AddWorker(const Worker& worker) {
  •            workers.push_back(worker);
  •        }
  •        vector<Worker> const& GetWorkers() const {
  •            return workers;
  •        }
  •    };
  •    struct BusinessManager {
  •    private:
  •        Business business;
  •    public:
  •        BusinessManager() {
  •            business = Business();
  •        }
  •        ~BusinessManager() = default;
  •        void AddWorker() {
  •            auto worker = Worker();
  •            cout << "Enter FIO: ";
  •            while(worker.fio.empty()) getline(cin, worker.fio);
  •            Date birthday{};
  •            cout << "Enter birthday (Day Month Year): ";
  •            cin >> birthday.day >> birthday.month >> birthday.year;
  •            worker.birthday = birthday;
  •            cout << "Enter job's name: ";
  •            while (worker.job.empty()) getline(cin, worker.job);
  •            cout << "Enter stage (unsig int numb): ";
  •            cin >> worker.stage;
  •            business.AddWorker(worker);
  •        }
  •        void FindWorkers() {
  •            auto workers = business.GetWorkers();
  •            Date today(7, 5, 2021);
  •            std::vector<std::vector<Worker>::const_iterator> matches;
  •            for (auto justWorker = workers.begin(); justWorker != workers.end(); ++justWorker){
  •                if ((today - justWorker->birthday).year >= 37 && justWorker->stage >= 10) {
  •                    matches.emplace_back(justWorker);
  •                }
  •            }
  •            for (auto & worker : matches) {
  •                auto buff = *worker;
  •                cout << "FIO: " << buff.fio << endl
  •                     << "Birthday: " << buff.birthday.day << "." << buff.birthday.month << "." << buff.birthday.year << endl
  •                     << "Job's title: " << buff.job << endl
  •                     << "Stage: " << buff.stage << endl << endl;
  •            }
  •        }
  •    };
  • }
  • int main () {
  •    using namespace business;
  •    BusinessManager manager;
  •    bool isStillRunning = true;
  •    while (isStillRunning) {
  •        cout << "[1] Add worker into company" << endl;
  •        cout << "[2] Find workers with age >= 37 and stage >= 10" << endl;
  •        cout << "[0] Exit" << endl;
  •        cout << "Your decision >> ";
  •        int decision = -1;
  •        cin >> decision;
  •        cout << endl;
  •        switch (decision) {
  •            case 0: isStillRunning = false; break;
  •            case 1: manager.AddWorker(); break;
  •            case 2: manager.FindWorkers(); break;
  •            default: cout << "[Warning] You enter some trash!" << endl << endl; continue;
  •        }
  •        cout << endl;
  •    }
  •    return 0;
  • }
0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Для выполнения этой задачи вы можете использовать структуры в C++ для представления данных о работниках и затем пройти по списку работников, фильтруя тех, кто соответствует вашим критериям. Вот пример кода:

cpp
#include <iostream> #include <string> #include <vector> #include <ctime> // Структура для представления данных о работнике struct Employee { std::string lastName; std::string firstName; std::string middleName; std::string birthDate; std::string position; int experience; // Стаж в годах }; int main() { // Создаем список работников std::vector<Employee> employees = { {"Иванов", "Иван", "Иванович", "01.01.1985", "Менеджер", 12}, {"Петров", "Петр", "Петрович", "15.06.1990", "Инженер", 8}, {"Сидоров", "Сидор", "Сидорович", "20.03.1978", "Директор", 15}, // Добавьте остальных работников }; // Получаем текущую дату time_t currentTime = time(nullptr); struct tm currentDate; localtime_s(&currentDate, &currentTime); // Определяем текущий год int currentYear = currentDate.tm_year + 1900; // Выводим информацию о работниках, соответствующих условиям std::cout << "Работники старше 37 лет с опытом более 10 лет:" << std::endl; for (const Employee& employee : employees) { // Разбираем дату рождения работника int birthYear = std::stoi(employee.birthDate.substr(6, 4)); // Вычисляем возраст работника int age = currentYear - birthYear; if (age > 37 && employee.experience >= 10) { std::cout << "Фамилия: " << employee.lastName << std::endl; std::cout << "Имя: " << employee.firstName << std::endl; std::cout << "Отчество: " << employee.middleName << std::endl; std::cout << "Дата рождения: " << employee.birthDate << std::endl; std::cout << "Должность: " << employee.position << std::endl; std::cout << "Стаж: " << employee.experience << " лет" << std::endl; std::cout << std::endl; } } return 0; }

В этом коде мы создаем структуру Employee, которая представляет данные о работнике, и затем создаем вектор работников. Мы вычисляем текущий год и проходим по списку работников, фильтруя тех, кто соответствует условиям (возраст более 37 лет и стаж более 10 лет), и выводим информацию о них на экран.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос