Лабораторные Армашев 3 семестр. Список оргтехники предприятия / лаба 4-5
.docxМИНОБРНАУКИ РОССИИ
Санкт-Петербургский государственный
электротехнический университет
«ЛЭТИ» им. В.И. Ульянова (Ленина)
КАФЕДРА РАПС
отчет
по лабораторным работам №(4-5)
по дисциплине «Программирование и основы алгоритмизации»
Студент группы 4404 |
________________ |
Комарницкий М.С. |
Преподаватель |
|
Армашев А.А. |
Санкт-Петербург
2025
Ход работы
Объявил в файле class.h классы для орг.техники, в том числе и для ремонта с поставками. Также были добавлены методы для работы с данными класса.
В файле class.c разработал методы для вывода данных, сохранения и загрузки в файл, расчёта амортизации товаров и вывода этой информации в отчёт.
Также была реализована функция поиска, удаления и редактирования данных.
class.h
#ifndef ORGTECHCLASS_H
#define ORGTECHCLASS_H
class OrgTechnic
{
public:
int id;
char category[50];
char model[100];
char purchaseDate[20];
int warrantyMonths;
float price;
char additionalInfo[200];
int coordX;
int coordY;
// Методы
bool IsWarrantyValid();
float CurrentValue();
int MonthsInUse();
void SetCoordinates(int x, int y);
// Методы для работы с файлами
void SaveToFile(FILE *file);
void LoadFromFile(FILE *file);
};
class Supply
{
public:
char supplier[100];
char category[50];
char model[100];
char supplyDate[20];
void SaveToFile(FILE *file);
void LoadFromFile(FILE *file);
};
class Repair
{
public:
int deviceId;
char category[50];
char model[100];
char repairStartDate[20];
char condition[100];
void SaveToFile(FILE *file);
void LoadFromFile(FILE *file);
};
class ReportCalculator
{
private:
OrgTechnic* devices;
int deviceCount;
public:
// Конструктор
ReportCalculator(OrgTechnic* devArray, int count);
// Методы для расчетов
float CalculateTotalOriginalValue();
float CalculateTotalCurrentValue();
float CalculateTotalDepreciation();
float CalculateDepreciationPercentage();
int CountDevicesWithWarranty();
int CountDevicesWithoutWarranty();
int GetTotalDevicesCount();
};
#endif
class.cpp
#include "class.h"
#include <string.h>
#include <cmath>
#include <ctime>
bool OrgTechnic::IsWarrantyValid()
{
return MonthsInUse() <= warrantyMonths;
}
float OrgTechnic::CurrentValue()
{
int monthsUsed = MonthsInUse();
if(monthsUsed <= warrantyMonths) {
return price * (1.0f - (monthsUsed * 0.005f));
} else {
int monthsAfterWarranty = monthsUsed - warrantyMonths;
float depreciation = (warrantyMonths * 0.005f) + (monthsAfterWarranty * 0.02f);
float value = price * (1.0f - depreciation);
return (value > price * 0.1f) ? value : price * 0.1f;
}
}
int OrgTechnic::MonthsInUse()
{
int day, month, year;
sscanf(purchaseDate, "%d.%d.%d", &day, &month, &year);
time_t t = time(NULL);
struct tm *currentTime = localtime(&t);
int currentYear = currentTime->tm_year + 1900;
int currentMonth = currentTime->tm_mon + 1;
return (currentYear - year) * 12 + (currentMonth - month);
}
void OrgTechnic::SetCoordinates(int x, int y)
{
coordX = x;
coordY = y;
}
void OrgTechnic::SaveToFile(FILE *file)
{
fprintf(file, "%d|%s|%s|%s|%d|%f|%s|%d|%d\n",
id, category, model, purchaseDate, warrantyMonths,
price, additionalInfo, coordX, coordY);
}
void OrgTechnic::LoadFromFile(FILE *file)
{
fscanf(file, "%d|%[^|]|%[^|]|%[^|]|%d|%f|%[^|]|%d|%d\n",
&id, category, model, purchaseDate, &warrantyMonths,
&price, additionalInfo, &coordX, &coordY);
}
void Supply::SaveToFile(FILE *file)
{
fprintf(file, "%s|%s|%s|%s\n",
supplier, category, model, supplyDate);
}
void Supply::LoadFromFile(FILE *file)
{
char line[300];
if (fgets(line, sizeof(line), file)) {
char* token = strtok(line, "|\n");
if (token) strcpy(supplier, token);
token = strtok(NULL, "|\n");
if (token) strcpy(category, token);
token = strtok(NULL, "|\n");
if (token) strcpy(model, token);
token = strtok(NULL, "|\n");
if (token) strcpy(supplyDate, token);
}
}
void Repair::SaveToFile(FILE *file)
{
fprintf(file, "%d|%s|%s|%s|%s\n",
deviceId, category, model, repairStartDate, condition);
}
void Repair::LoadFromFile(FILE *file)
{
char line[300];
if (fgets(line, sizeof(line), file)) {
char* token = strtok(line, "|\n");
if (token) deviceId = atoi(token);
token = strtok(NULL, "|\n");
if (token) strcpy(category, token);
token = strtok(NULL, "|\n");
if (token) strcpy(model, token);
token = strtok(NULL, "|\n");
if (token) strcpy(repairStartDate, token);
token = strtok(NULL, "|\n");
if (token) strcpy(condition, token);
}
}
// Конструктор
ReportCalculator::ReportCalculator(OrgTechnic* devArray, int count)
{
devices = devArray;
deviceCount = count;
}
// Общая первоначальная стоимость
float ReportCalculator::CalculateTotalOriginalValue()
{
float total = 0.0f;
for(int i = 0; i < deviceCount; i++) {
total += devices[i].price;
}
return total;
}
// Общая текущая стоимость
float ReportCalculator::CalculateTotalCurrentValue()
{
float total = 0.0f;
for(int i = 0; i < deviceCount; i++) {
total += devices[i].CurrentValue();
}
return total;
}
// Общая амортизация
float ReportCalculator::CalculateTotalDepreciation()
{
return CalculateTotalOriginalValue() - CalculateTotalCurrentValue();
}
// Процент амортизации
float ReportCalculator::CalculateDepreciationPercentage()
{
float original = CalculateTotalOriginalValue();
if(original == 0) return 0.0f;
return (CalculateTotalDepreciation() / original) * 100.0f;
}
// Количество устройств с гарантией
int ReportCalculator::CountDevicesWithWarranty()
{
int count = 0;
for(int i = 0; i < deviceCount; i++) {
if(devices[i].IsWarrantyValid()) {
count++;
}
}
return count;
}
// Количество устройств без гарантии
int ReportCalculator::CountDevicesWithoutWarranty()
{
return deviceCount - CountDevicesWithWarranty();
}
// Общее количество устройств
int ReportCalculator::GetTotalDevicesCount()
{
return deviceCount;
}
ControlListTech.cpp (часть)
void TFormControlListTech::ShowEditDialog(int deviceIndex)
{
int deviceId = devices[deviceIndex].id;
char oldModel[100], oldCategory[50];
strcpy(oldModel, devices[deviceIndex].model);
strcpy(oldCategory, devices[deviceIndex].category);
TForm* editForm = new TForm(this);
editForm->Caption = "Редактирование оборудования";
editForm->Width = 650;
editForm->Height = 550;
editForm->Position = poScreenCenter;
TLabel* lblCategory = new TLabel(editForm);
lblCategory->Parent = editForm;
lblCategory->Left = 20;
lblCategory->Top = 20;
lblCategory->Caption = "Категория:";
TEdit* edtCategory = new TEdit(editForm);
edtCategory->Parent = editForm;
edtCategory->Left = 140;
edtCategory->Top = 20;
edtCategory->Width = 400;
edtCategory->Text = devices[deviceIndex].category;
TLabel* lblModel = new TLabel(editForm);
lblModel->Parent = editForm;
lblModel->Left = 20;
lblModel->Top = 60;
lblModel->Caption = "Модель:";
TEdit* edtModel = new TEdit(editForm);
edtModel->Parent = editForm;
edtModel->Left = 140;
edtModel->Top = 60;
edtModel->Width = 400;
edtModel->Text = devices[deviceIndex].model;
TLabel* lblDate = new TLabel(editForm);
lblDate->Parent = editForm;
lblDate->Left = 20;
lblDate->Top = 100;
lblDate->Caption = "Закупка:";
TEdit* edtDate = new TEdit(editForm);
edtDate->Parent = editForm;
edtDate->Left = 140;
edtDate->Top = 100;
edtDate->Width = 400;
edtDate->Text = devices[deviceIndex].purchaseDate;
TLabel* lblWarranty = new TLabel(editForm);
lblWarranty->Parent = editForm;
lblWarranty->Left = 20;
lblWarranty->Top = 140;
lblWarranty->Caption = "Гарантия:";
TEdit* edtWarranty = new TEdit(editForm);
edtWarranty->Parent = editForm;
edtWarranty->Left = 140;
edtWarranty->Top = 140;
edtWarranty->Width = 400;
edtWarranty->Text = IntToStr(devices[deviceIndex].warrantyMonths);
TLabel* lblPrice = new TLabel(editForm);
lblPrice->Parent = editForm;
lblPrice->Left = 20;
lblPrice->Top = 180;
lblPrice->Caption = "Цена:";
TEdit* edtPrice = new TEdit(editForm);
edtPrice->Parent = editForm;
edtPrice->Left = 140;
edtPrice->Top = 180;
edtPrice->Width = 400;
edtPrice->Text = FloatToStr(devices[deviceIndex].price);
TLabel* lblInfo = new TLabel(editForm);
lblInfo->Parent = editForm;
lblInfo->Left = 20;
lblInfo->Top = 220;
lblInfo->Caption = "Доп. информация:";
TMemo* memInfo = new TMemo(editForm);
memInfo->Parent = editForm;
memInfo->Left = 20;
memInfo->Top = 260;
memInfo->Width = 550;
memInfo->Height = 100;
memInfo->Text = devices[deviceIndex].additionalInfo;
TButton* btnOk = new TButton(editForm);
btnOk->Parent = editForm;
btnOk->Left = 150;
btnOk->Top = 370;
btnOk->Width = 150;
btnOk->Height = 50;
btnOk->Caption = "Сохранить";
btnOk->ModalResult = mrOk;
TButton* btnCancel = new TButton(editForm);
btnCancel->Parent = editForm;
btnCancel->Left = 310;
btnCancel->Top = 370;
btnCancel->Width = 150;
btnCancel->Height = 50;
btnCancel->Caption = "Отмена";
btnCancel->ModalResult = mrCancel;
if (editForm->ShowModal() == mrOk) {
AnsiString category = edtCategory->Text;
AnsiString model = edtModel->Text;
AnsiString date = edtDate->Text;
AnsiString info = memInfo->Text;
strcpy(devices[deviceIndex].category, category.c_str());
strcpy(devices[deviceIndex].model, model.c_str());
strcpy(devices[deviceIndex].purchaseDate, date.c_str());
devices[deviceIndex].warrantyMonths = StrToInt(edtWarranty->Text);
devices[deviceIndex].price = StrToFloat(edtPrice->Text);
strcpy(devices[deviceIndex].additionalInfo, info.c_str());
int updatedRepairs = 0;
for(int i = 0; i < repairCount; i++) {
if (repairs[i].deviceId == deviceId) {
strcpy(repairs[i].category, category.c_str());
strcpy(repairs[i].model, model.c_str());
updatedRepairs++;
}
}
int updatedSupplies = 0;
for(int i = 0; i < supplyCount; i++) {
if (strcmp(supplies[i].model, oldModel) == 0 && strcmp(supplies[i].category, oldCategory) == 0) {
strcpy(supplies[i].category, category.c_str());
strcpy(supplies[i].model, model.c_str());
updatedSupplies++;
}
}
SaveToFile();
UpdateMainListView();
UpdateRepairsListView();
UpdateSuppliesListView();
sample_pb->Repaint();
String message = "Оборудование обновлено: " + String(devices[deviceIndex].model);
if (updatedRepairs > 0) {
message += "\nОбновлено записей о ремонтах: " + IntToStr(updatedRepairs);
}
if (updatedSupplies > 0) {
message += "\nОбновлено записей о поставках: " + IntToStr(updatedSupplies);
}
ShowMessage(message);
}
delete editForm;
}
void TFormControlListTech::UpdateReportTab()
{
if(deviceCount == 0) {
Label3->Caption = " Нет данных для отчета.\nСначала загрузите файл!.";
return;
}
ReportCalculator calculator(devices, deviceCount);
String reportText;
reportText = "ОТЧЕТ ПО СТОИМОСТИ ОБОРУДОВАНИЯ\n\n";
reportText += "Общее количество оборудования: " + IntToStr(calculator.GetTotalDevicesCount()) + "\n";
reportText += "• С действующей гарантией: " + IntToStr(calculator.CountDevicesWithWarranty()) + "\n";
reportText += "• Без гарантии: " + IntToStr(calculator.CountDevicesWithoutWarranty()) + "\n\n";
reportText += "ФИНАНСОВЫЕ ПОКАЗАТЕЛИ:\n";
reportText += "• Первоначальная стоимость: " + FloatToStrF(calculator.CalculateTotalOriginalValue(), ffFixed, 12, 2) + " руб.\n";
reportText += "• Текущая стоимость: " + FloatToStrF(calculator.CalculateTotalCurrentValue(), ffFixed, 12, 2) + " руб.\n";
reportText += "• Общая амортизация: " + FloatToStrF(calculator.CalculateTotalDepreciation(), ffFixed, 12, 2) + " руб.\n";
reportText += "• Процент амортизации: " + FloatToStrF(calculator.CalculateDepreciationPercentage(), ffFixed, 5, 1) + "%\n\n";
reportText += "Отчет обновлен: " + FormatDateTime("dd.mm.yyyy hh:nn:ss", Now());
Label3->Caption = reportText;
}
// ОБРАБОТЧИК СМЕНЫ ВКЛАДКИ
void __fastcall TFormControlListTech::PageControl1Change(TObject *Sender)
{
// Если переключились на вкладку отчета (TabSheet3)
if (PageControl1->ActivePage == TabSheet3) {
UpdateReportTab(); // Обновляем отчет
}
}
