Практическая работа №12. Тема: Разработка программ со структурированными типами данных. Цель: Получить навыки работы со структурированными типами данных. Оборудование: IBM PC. Программное обеспечение: Borland C++ Builder 6. Вариант 8. Порядок выполнения работы: 1. Открыл среду программирования, начал разработку нового проекта. 2. Создал приложение, подключил необходимые модули и отладил его: #include <math.h> #include <stdio.h> Задание №1. Составить программу, с использованием структур для выполнения задания: Даны две простые дроби. Найти их частное. Сократить полученную дробь, если это возможно struct chastnoe {int chisl, znam;}; void __fastcall TForm1::Button1Click(TObject *Sender) {chastnoe ch1,ch2,ch3,ch4; int i; ch1.chisl=StrToInt(Edit1->Text); ch1.znam=StrToInt(Edit2->Text); ch2.chisl=StrToInt(Edit3->Text); ch2.znam=StrToInt(Edit4->Text); ch3.chisl=ch1.chisl*ch2.znam; ch3.znam=ch1.znam*ch2.chisl; ch4.chisl=ch3.chisl; ch4.znam=ch3.znam; while (ch4.chisl!=ch4.znam) {if (ch4.chisl>ch4.znam) ch4.chisl-=ch4.znam; else ch4.znam-=ch4.chisl;} ch3.chisl/=ch4.znam; ch3.znam/=ch4.znam; Edit5->Text=IntToStr(ch3.chisl); Edit6->Text=IntToStr(ch3.znam); } Задание №2. Составить программу с использованием структур для выполнения задания. Исходные списки в программе описать в виде массовов структур. Обеспечить сохранение структурированных данных в файле на диске: В магазине имеется список поступивших в продажу автомобилей. Каждая запись этого списка содержит марку автомобиля и его параметы: стоимость, расход бензина на 100км, надежность (число лет безотказной работы), комфортность (отличная, хорошая, удовлетрорительная). Покупатель, в свою очередь, имеет ряд требований по каждому из этих параметров. Эти требования задаются в виде некоторого интервала (например, стоимость 10..30 тыс $; расход бензина 4..10 л на 100км). Вывести на печать перечень автомобилей, удовлетворяющих требованием покупателя. Требования покупателя ввести с клавиатуры struct autom{AnsiString marka,komfort; int rashod,stoimost,nadezn;}; struct search {int ott,doo; AnsiString strott,strdoo;}; void __fastcall TForm1::LabeledEdit1Exit(TObject *Sender) {StringGrid1->RowCount=1+StrToInt(LabeledEdit1->Text) ;} void __fastcall TForm1::FormCreate(TObject *Sender) {LabeledEdit1->Text=IntToStr(StringGrid1->RowCount)-1; StringGrid1->Cells[0][0]="Ìàðêà àâòîìîáèëÿ"; StringGrid1->Cells[1][0]="Ñòîèìîñòü òûñÿ÷ $"; StringGrid1->Cells[2][0]="Ðàñõîä ëèòðîâ áåíçèíà íà 100 êì"; StringGrid1->Cells[3][0]="Íàäåæíîñòü (ëåò)"; StringGrid1->Cells[4][0]="Êîìôîðòíîñòü"; StringGrid2->Cells[0][0]=StringGrid1->Cells[1][0]; StringGrid2->Cells[1][0]=StringGrid1->Cells[2][0]; StringGrid2->Cells[2][0]=StringGrid1->Cells[3][0]; StringGrid2->Cells[3][0]=StringGrid1->Cells[4][0];} void __fastcall TForm1::Button1Click(TObject *Sender) { int i; search S_stoimost,S_rashod,S_nadezn,S_komfort; FILE *S_cars; autom mn[100]; for (i=1;i<StringGrid1->RowCount;i++) {mn[i].marka=StringGrid1->Cells[0][i]; mn[i].stoimost=StrToInt(StringGrid1->Cells[1][i]); mn[i].rashod=StrToInt(StringGrid1->Cells[2][i]); mn[i].nadezn=StrToInt(StringGrid1->Cells[3][i]); mn[i].komfort=StringGrid1->Cells[4][i];} try {S_stoimost.ott=StrToInt(StringGrid2->Cells[0][1].SubString(1,StringGrid2->Cells[0][1].Pos('.')-1)); S_stoimost.doo=StrToInt(StringGrid2->Cells[0][1].SubString(StringGrid2->Cells[0][1].Pos('.')+2,StringGrid2->Cells[0][1].Length())); S_rashod.ott=StrToInt(StringGrid2->Cells[1][1].SubString(1,StringGrid2->Cells[1][1].Pos('.')-1)); S_rashod.doo=StrToInt(StringGrid2->Cells[1][1].SubString(StringGrid2->Cells[1][1].Pos('.')+2,StringGrid2->Cells[1][1].Length())); S_nadezn.ott=StrToInt(StringGrid2->Cells[2][1].SubString(1,StringGrid2->Cells[2][1].Pos('.')-1)); S_nadezn.doo=StrToInt(StringGrid2->Cells[2][1].SubString(StringGrid2->Cells[2][1].Pos('.')+2,StringGrid2->Cells[2][1].Length())); S_komfort.strott=StringGrid2->Cells[3][1].SubString(1,StringGrid2->Cells[3][1].Pos('.')-1); S_komfort.strdoo=StringGrid2->Cells[3][1].SubString(StringGrid2->Cells[3][1].Pos('.')+2,StringGrid2->Cells[3][1].Length()); } catch (...) {ShowMessage("Íå ïðàâèëüíî ââåäåíû êðèòåðèè ïîèñêà. Íåîáõîäèìî äèàïàçîíû óêàçûâàòü ÷åðåç .., íàïðèìåð 11..12");} SaveDialog1->Execute(); if (SaveDialog1->FileName!="") {S_cars=fopen(strdup(SaveDialog1->FileName.c_str()),"wt"); fprintf(S_cars,"Ñòîèìîñòü_òûñÿ÷_$ Ðàñõîä Íàäåæíîñòü(ëåò) Êîìôîðòíîñòü Ìàðêà_àâòîìîáèëÿ"); for (i=1;i<=StringGrid1->RowCount;i++) if (((mn[i].stoimost>=S_stoimost.ott) && (mn[i].stoimost<=S_stoimost.doo)) && ((mn[i].rashod>=S_rashod.ott) && (mn[i].rashod<=S_rashod.doo)) && ((mn[i].nadezn>=S_nadezn.ott) && (mn[i].nadezn<=S_nadezn.doo)) && ((mn[i].komfort==S_komfort.strott) || (mn[i].komfort==S_komfort.strdoo))) {ShowMessage(mn[i].marka+" "+IntToStr(mn[i].stoimost)+" "+IntToStr(mn[i].rashod)+" "+IntToStr(mn[i].nadezn)+" "+mn[i].komfort); fprintf(S_cars,"\n %i %i %i %s %s",mn[i].stoimost,mn[i].rashod,mn[i].nadezn,mn[i].komfort,mn[i].marka); }} fclose(S_cars); } void __fastcall TForm1::StringGrid1Click(TObject *Sender) { Int i,k;AnsiString; cars[]={"Audi","Volkswagen","Mercedes","BMW","Porsche","Toyota","Skoda","Mazda","Opel","Honda"}, komf[]={"îòëè÷íàÿ","õîðîøàÿ","óäîâëåòâîðèòåëüíàÿ"}; randomize(); for (i=1;i<StringGrid1->RowCount;i++) {StringGrid1->Cells[0][i]=cars[random(10)]; StringGrid1->Cells[1][i]=random(30); StringGrid1->Cells[2][i]=random(15); StringGrid1->Cells[3][i]=random(40); StringGrid1->Cells[4][i]=komf[random(3)]; } } 3. Сохранил проект. Удалил временные файлы. Вывод: Я получил навыки работы со структурированными типами данных.
1/--страниц