Академический Документы
Профессиональный Документы
Культура Документы
ЛУГАНСКОЙ НАРОДНОЙ РЕСПУБЛИКИ
ГОУ ВПО ЛНР "ЛУГАНСКИЙ НАЦИОНАЛЬНЫЙ УНИВЕРСИТЕТ
ИМЕНИ ВЛАДИМИРА ДАЛЯ"
Кафедра "Автоматизация и компьютерно-интегрированные технологии"
Лабораторная работа
Группа ИТ-381
Защищено с оценкой
Луганск, 2019
Лаба 1==========================================
}
int main()
{
//1
{
int keks[6] = { 1,9,6,4,8,5 };
int nmax = max_num(max_num(max_num(keks[0], keks[1]), max_num(keks[2], keks[3])), max_num(keks[4], keks[5]));
cout << nmax;
}
cout << endl;
//2,3
draw_text('*', 80);
cout << endl;
//4
cout << get_quarter(7, 9);
cout << endl;
//5/6
cout << check_year(2019);
cout << endl;
//7
cout << get_days(2);
cout << endl;
//8
randstr("qw532", 20);
cout << endl;
//9
cout << get_fact(10);
cout << endl;
//10
cout << reverse_num(565763);
cout << endl;
//11
cout << simm_str("keeeek");
cout << endl;
}
Вывод: изучил назначение и способы организации функций и способы написания функций с многократным входом.
Лаба 2==========================================
1. int mas1[20], counter = 0, counter2 = 0;
for (int i = 0; i < 20; i++)
{
mas1[i] = rand() % 14;
if (!(mas1[i] % 2))
counter++;
cout << mas1[i] << " ";
}
cout << endl;
int* mas2 = new int[counter];
for (int i = 0; i < 20; i++)
{
if (!(mas1[i] % 2))
{
mas2[counter2] = mas1[i];
cout << mas2[counter2++] << " ";
}
}
cout << endl;
Вывод: при помощи операции new, выделил в динамической памяти участок для размещения массива соответствующего типа.
Лаба 3================================================================
////////////////////////////////////////////////////////////////
/////////////////////////// 1 //////////////////////////////////
////////////////////////////////////////////////////////////////
class student
{
public:
string firstname;
string lastname;
int group;
int rating[5];
student()
{
firstname = "Имя";
lastname = "НеИмя";
group = 381;
}
double average()
{
return (rating[0] + rating[1] + rating[2] + rating[3] + rating[4]) / (double)5;
}
void showcool()
{
bool cool = true;
for (int i = 0; i < 5; i++)
if (rating[i] < 4) cool = false;
if (cool)
cout << "Имя:" << firstname << endl << "Фамилия: " << lastname << endl << "Группа:" << group << endl;
}
};
void swapst(student* first, student* second)
{
student temp;
temp.firstname = first->firstname;
temp.lastname = first->lastname;
temp.group = first->group;
for (int i = 0; i < 5; i++)
temp.rating[i] = first->rating[i];
first->firstname = second->firstname;
first->lastname = second->lastname;
first->group = second->group;
for (int i = 0; i < 5; i++)
first->rating[i] = second->rating[i];
second->firstname = temp.firstname;
second->lastname = temp.lastname;
second->group = temp.group;
for (int i = 0; i < 5; i++)
second->rating[i] = temp.rating[i];
}
int main()
{
setlocale(LC_ALL, "rus");
srand(time(0));
/* 1
//Создать массив
student students[10];
for (int ii = 0; ii < 10; ii++)
for (int i = 0; i < 5; i++)
students[ii].rating[i] = rand() % 4 + 2;
//упорядочить записи по возрастанию среднего балла
for (int i = 0; i < 10; i++)
cout << students[i].average() << " ";
cout << endl;
for (int i = 0; i < 9; i++)
if(students[i].average() > students[i+1].average())
{
swapst(&students[i], &students[i + 1]);
i = 0;
}
else if (students[0].average() > students[1].average())
{
swapst(&students[0], &students[1]);
i = 0;
}
cout << endl;
for (int i = 0; i < 10; i++)
cout << students[i].average() << " ";
////////////////////////////////////////////////////////////////
/////////////////////////// 2 //////////////////////////////////
////////////////////////////////////////////////////////////////
enum city
{
Lugansk, Moscow, Kiev, Minsk
};
class train
{
public:
int city;
int id;
int start_ts;
string showcity()
{
if (city == Lugansk) return "Lugansk";
if (city == Moscow) return "Moscow";
if (city == Kiev) return "Kiev";
if (city == Minsk) return "Minsk";
}
void showinfo()
{
cout << id << " | " << showcity() << " | " << start_ts << endl;
}
};
first->city = second->city;
first->id = second->id;
first->start_ts = second->start_ts;
second->city = temp.city;
second->id = temp.id;
second->start_ts = temp.start_ts;
int main()
{
setlocale(LC_ALL, "rus");
srand(time(0));
/* 2
//Создать массив
train trains[5];
for (int ii = 0; ii < 5; ii++)
{
trains[ii].start_ts = time(0) + rand() % 100;
trains[ii].id = rand() % 10;
for (int i = 0; i < ii; i++)
{
if (trains[ii].id == trains[i].id)
ii--;
}
}
trains[0].city = Lugansk;
trains[1].city = Kiev;
trains[2].city = Lugansk;
trains[3].city = Moscow;
trains[4].city = Kiev;
//сортировка массива по пункту назначения, причем поезда с одинаковыми пунктами назначения должны быть упорядочены по времени
отправления.
for (int i = 0; i < 5; i++)
trains[i].showinfo();
cout << endl;
////////////////////////////////////////////////////////////////
/////////////////////////// 3 //////////////////////////////////
////////////////////////////////////////////////////////////////
class twoints
{
public:
int first;
int second;
void show()
{
cout << first << " | " << second << endl;
}
int sum()
{
return first + second;
}
int biggest()
{
if (first == second)
return -1;
if (first > second)
return first;
else
return second;
}
};
int main()
{
setlocale(LC_ALL, "rus");
srand(time(0));
/* 3
twoints keks;
keks.first = rand() % 50;
keks.second = rand() % 50;
keks.show();
keks.edit(rand() % 50, rand() % 50);
keks.show();
cout << "Sum:" << keks.sum() << " | " << "Biggest:" << keks.biggest() << endl;
*/
}
////////////////////////////////////////////////////////////////
/////////////////////////// 4 //////////////////////////////////
////////////////////////////////////////////////////////////////
class g_counter
{
public:
unsigned int counter;
unsigned int min;
unsigned int max;
g_counter(int startfrom = 0)
{
counter = startfrom;
min = 0;
max = 0xFFFFFFFF;
}
g_counter(int _min, int _max, int startfrom = 0)
{
counter = startfrom;
if (_min >= _max)
cout << "error min > max";
if (startfrom < _min || startfrom > _max)
cout << "startfrom out of range";
min = _min;
max = _max;
}
void inc()
{
if (counter < max)
counter++;
else
cout << "counter max" << endl;
}
void dec()
{
if (counter > min)
counter--;
else
cout << "counter min" << endl;
}
void show()
{
cout << "Counter:" << counter;
if (counter == max) cout << " | MAX";
else if(counter == min) cout << " | MIN";
cout << endl;
}
};
int main()
{
setlocale(LC_ALL, "rus");
srand(time(0));
/* 4
g_counter count(1, 5, 2);
for (int i = 0; i < 10; i++)
{
count.inc();
count.show();
}
count.dec();
count.dec();
count.show();
*/
}
////////////////////////////////////////////////////////////////
/////////////////////////// 5 //////////////////////////////////
////////////////////////////////////////////////////////////////
class twoptrs
{
public:
int first;
int second;
twoptrs()
{
first = 0;
second = 0;
}
twoptrs(int _first, int _second)
{
first = _first;
second = _second;
}
~twoptrs()
{
cout << "Destructor called";
}
};
int main()
{
setlocale(LC_ALL, "rus");
srand(time(0));
/* 5
twoptrs* keks = new twoptrs();
twoptrs keksik(10,20);
delete keks;
}
////////////////////////////////////////////////////////////////
/////////////////////////// 6 //////////////////////////////////
////////////////////////////////////////////////////////////////
class dynarr
{
public:
int* arr;
int cnt;
void randarr()
{
for (int i = 0; i < cnt; i++)
arr[i] = rand() % 90 + 10;
}
void swap(int _findex, int _sindex)
{
int temp;
temp = arr[_findex];
arr[_findex] = arr[_sindex];
arr[_sindex] = temp;
}
int razl()
{
int* temp = new int[cnt];
int counter = 0;
for (int i = 0; i < cnt; i++)
{
temp[i] = -1;
}
bool est = false;
for (int i = 0; i < cnt; i++)
{
void showarr()
{
for (int i = 0; i < cnt; i++)
cout << arr[i] << " ";
cout << endl;
}
};
int main()
{
setlocale(LC_ALL, "rus");
srand(time(0));
/* 6
dynarr d_array(10);
//d_array.showarr();
d_array.randarr();
d_array.showarr();
d_array.swap(0, 1);
d_array.showarr();
cout << d_array.razl();
*/
}
////////////////////////////////////////////////////////////////
/////////////////////////// 7 //////////////////////////////////
////////////////////////////////////////////////////////////////
enum fType
{
Meat, Grass, All
};
class zoo
{
public:
string name;
int foodcnt[3];
int sitost;
int type;
virtual void food(int animalcnt) = 0;
virtual void getinfo(int animalcnt) = 0;
zoo()
{
cout << "zoo created" << endl;
sitost = 0;
}
};
class onlyMeat : public zoo
{
public:
onlyMeat()
{
cout << "onlyMeat created" << endl;
foodcnt[Meat] = 500;
}
int need = 5;
void food(int animalcnt)
{
sitost += need * animalcnt;
foodcnt[Meat] -= need * animalcnt;
}
void getinfo(int animalcnt)
{
cout << "Нужно потратить " << need * animalcnt << " мяса" << endl;
}
};
class onlyGrass : public zoo
{
public:
onlyGrass()
{
cout << "onlyGrass created" << endl;
foodcnt[Grass] = 500;
}
int need = 2;
void food(int animalcnt)
{
sitost += need * animalcnt;
foodcnt[Grass] -= need * animalcnt;
}
void getinfo(int animalcnt)
{
cout << "Нужно потратить " << need * animalcnt << " травы" << endl;
}
};
class allGrassMeat : public zoo
{
public:
allGrassMeat()
{
cout << "allGrassMeat created" << endl;
foodcnt[All] = 500;
}
int need = 3;
void food(int animalcnt)
{
sitost += need * animalcnt;
foodcnt[All] -= need * animalcnt;
}
void getinfo(int animalcnt)
{
cout << "Нужно потратить " << need * animalcnt << " еды" << endl;
}
};
Вывод: изучил основы объектно-ориентированного программирования и научился проектировать сложные структуры данных, изучил основы
проектирование классов при наследовании.
Лаба 5==========================================================
// 1
int _tmain(int argc, _TCHAR* argv[])
{
setlocale (LC_ALL,"Russian");
//fstream file;
//file.open ("test.txt");
//int c;
//cin>>c;
//if(c==1){
//int a;
//file>>a;
//cout<<a<<" ";
//cout<<endl;
//cout<<endl;}
//if(c==2){
//
// ofstream file;
//file.open("test.txt");
//int b[10];
//for(int i=0;i<10;i++)
// {
// b[i]=rand()%20;
// if(b[i]%2!=0)
// file<<b[i];
// cout<<b[i]<<" ";
//}
//}
//2
/*fstream file;
file.open("qwe.txt");
int b;
cin>>b;
if(b==1){
char a;
while(file.get(a))
{
cout<<a;
}
}
if(b==2){
ofstream file;
file.open("qwe.txt");
char a[5];
for(int i=0;i<sizeof(a);i++){
cin>>a[i];
if(a[i]!='0'){
file<<a[i];}
}
}*/
//3
/*fstream file;
file.open("1.txt");
char b[5];
for(int i=0;i<5;i++){
file>>b[i];
cout<<b[i];
ofstream file2;
file2.open("2.txt");
int t=5;
for(int i=1;i<=5;i++){
t--;
file2<<b[t];
cout<<b[t];}
}*/
//4
//fstream file;
//file.open("num1.txt");
//ofstream fileall;
//fileall.open("numall.txt");
//int a[10];
//int c[10];
//for(int i=0;i<10;i++)
//{
// file>>a[i];
// if(a[i]<5){
// //cout<<a[i];
// fileall<<a[i];}
//}
//cout<<endl;
// fstream file2;
//file2.open("num2.txt");
//for(int i=0;i<10;i++){
// file2>>c[i];
// if(c[i]>5){
// //cout<<c[i];
// fileall<<c[i];}
//}
//6
/*fstream file;
file.open("Mat.txt");
int a[2][3];
int v[3][2];
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
file>>a[i][j];
v[j][i]=a[i][j];ы
}
cout<<endl;
}
for(int i=0;i<3;i++){
for(int j=0;j<2;j++){
cout<<v[i][j];
}
cout<<endl;
}*/
system("pause");
return 0;
}
//7
/*void chel()
{
string n;
string b;
string q;
cout<<"Введите фамилию: ";
getline(cin, n);
cout<<endl;
cout<<"Год покупки номера: ";
getline(cin, b);
cout<<endl;
cout<<"Номер телефона: ";
getline(cin, q);
cout<<endl;
ofstream file;
file.open("Tezt.txt", fstream::app);
file<<endl;
file<<n<<" ";
file<<b<<" ";
file<<q<<" ";
file<<endl;
}
void show(string n,string b,string q)
{
cout<<n<<b<<q;
}*/
int _tmain(int argc, _TCHAR* argv[])
{
setlocale (LC_ALL,"Russian");
//7
/*fstream file;
file.open("Tezt.txt", fstream::in | fstream::out | fstream::app);
cout<<"1-запись в файл"<<endl;
cout<<"2-прочитать файл, выбрав фамилию"<<endl;
cout<<"3-прочитать файл, выбрав год"<<endl;
string sur;
getline(cin,sur);
if(sur=="1")
{
chel();
}
if(sur=="2")
{
for(int i=0;i<100;i++){
cout<<"Введите фамилию: ";
char fam[100];
cin>>fam;
ifstream input("Tezt.txt");
char buffer[1024];
while(input.getline(buffer,1024)) {
if(strstr(buffer, fam))
cout << buffer << endl;
}
}
}
if(sur=="3")
{
cout<<"Введите год: ";
for(int i=0;i<100;i++){
char year[5];
cin>>year;
ifstream input("Tezt.txt");
char buffer[1024];
while(input.getline(buffer,1024)) {
if(strstr(buffer, year))
cout << buffer << endl;
}
}
}*/
//8
/*char fam_s[2]="S";
char fam_k[2]="K";
ifstream input("IZ.txt");
fstream file("V.txt", ios::app);
char buffer[1024];
while(input.getline(buffer,1024)) {
if(strstr(buffer, fam_k))
file<<buffer<<endl;
if(strstr(buffer, fam_s))
file<<buffer<<endl;
} */
// 9
//ifstream file("1.dat");
//string vibor;
//cout<<"1-поиск изделия в наличии"<<endl;
//cout<<"2-узнать общую стоимость всех изделий"<<endl;
//cout<<"3-узнать номер изделия и название"<<endl;
//cout<<"4-узнать информацию об изделии по букве"<<endl;
//getline(cin,vibor);
//if(vibor=="1")
//{
//cout<<"Введите номер Изделия"<<endl;
//string str;
//int i=1;
//int n;
//cin>>n;
//while (getline(file, str))
// {
// if (i == n)
// {
// cout << "В наличии" <<endl;
// break;
// }
// i++;
// }
//}
//if(vibor=="2")
//{
// ifstream file("1.dat");
// string line;
// string name;
// int cum=0;
// int num, kol, cost_one,cost;
//
// while(getline(file,line))
// {
// istringstream iss(line);
// iss>>num>>name>>kol>>cost_one>>cost;
// cum+=cost;
// }
// cout<<"Summa всех изделий: "<<cum;
//}
//if(vibor=="3")
//{
// ifstream file("1.dat");
// string line;
// string name;
// int cum=0;
// int num, kol, cost_one,cost;
//
// while(getline(file,line))
// {
// istringstream iss(line);
// iss>>num>>name>>kol>>cost_one>>cost;
// cout<<num<<endl;
// cout<<name<<endl;
// cout<<endl;
// }
//}
//if(vibor=="4")
//{
// cout<<"Введите букву, изделия которого вы хотите получить"<<endl;
// char let[2];
// cin>>let;
// ifstream input("1.dat");
//char buffer[1024];
//while(input.getline(buffer,1024)) {
//if(strstr(buffer, let))
//cout<<buffer;
//}
//}
Вывод: изучил применение потоков ввода-вывода для работы с файлами, изучить способы записи и чтения структурированных данных.
Лаба 6==============================================================
1)
template<typename T>
class List
{
public:
List();
~List();
void clear();
void pop_front();
void push_back(T data);
int GetSize ()
{
return Size;
}
private:
template <typename T>
class Node
{
public:
Node *pNext;
T data;
template<typename T>
List<T>::~List()
{
cout<<"Destructor";
clear();
}
template<typename T>
void List<T>::push_back(T data)
{
if(head == nullptr)
{
head = new Node<T>(data);
}
else
{
Node<T> *current = this->head;//от головы указываем на след. элемент
while(current->pNext !=nullptr)//если след. элемент не 0, в нашем случае 10.
{
current=current->pNext;
}
current->pNext= new Node<T>(data);// нов. элемент в конец списка
Size++;
}
template<typename T>
T & List<T>::operator[](const int index)
{
int counter =0;
Node <T> *current = this->head;
while(current!=nullptr)
{
if(counter == index)
{
return current->data;
}
current = current->pNext;
counter++;
}
}
template<typename T>
void List<T>::pop_front()
{
Node<T> *temp = head;
head=head->pNext;
delete temp;//delete бывшую head;
Size--;
}
template<typename T>
void List<T>::clear()
{
while(Size)
{
pop_front();
}
}
List<int> lst;
int num;
cin>>num;
cout<<endl;
for(int i=0;i<num;i++)
{
lst.push_back(rand()%10);
}
for(int i=0;i<lst.GetSize();i++)
{
cout<<lst[i]<<endl;
}
system("pause");
return 0;
}
2)
struct Node
{
int x;
Node *Next, *Prev;
};
class List
{
Node *Head, *Tail;
public:
List():Head(NULL),Tail(NULL){};
~List();
void Show();
void Add(int x);
};
List::~List()
{
while (Head)
{
Tail = Head->Next;
delete Head;
Head = Tail;
}
}
void List::Add(int x)
{
Node *temp = new Node;
temp->Next = NULL;
temp->x = x;
if (Head != NULL)
{
temp->Prev = Tail;
Tail->Next = temp;
Tail = temp;
}
else //Если список пустой
{
temp->Prev = NULL;
Head = Tail = temp;
}
}
void List::Show()
{
Node *temp=Tail;
List lst;
lst.Add(100);
lst.Add(200);
lst.Add(900);
lst.Add(888);
lst.Show();
system("pause");
return 0;
}
3)
struct DoubleList
{
int data;
DoubleList *next;
DoubleList *prev;
};
DoubleList *head;
//**********************ДОБАВЛЕНИЕ ЭЛЕМЕНТА**********************
void AddList(int value, int position)
{
DoubleList *node=new DoubleList;
node->data=value;
if (head==NULL)
{
node->next=node;
node->prev=node;
head=node;
}
else
{
DoubleList *p=head;
for(int i=position; i>1; i--) p=p->next;
p->prev->next=node;
node->prev=p->prev;
node->next=p;
p->prev=node;
}
cout<<"\nЭлемент добавлен...\n\n";
}
int DeleteList(int position)
{
if (head==NULL) { cout<<"\nСписок пуст\n\n"; return 0; }
if (head==head->next)
{
delete head;
head=NULL;
}
else
{
DoubleList *a=head;
for (int i=position; i>1; i--) a=a->next;
if (a==head) head=a->next;
a->prev->next=a->next;
a->next->prev=a->prev;
delete a;
}
cout<<"\nЭлемент удален...\n\n";
}
void PrintList()
{
if (head==NULL) cout<<"\nСписок пуст\n\n";
else
{
DoubleList *a=head;
cout<<"\nЭлементы списка: ";
do
{
cout<<a->data<<" ";
a=a->next;
} while(a!=head); cout<<"\n\n";
}
}
system("pause>NUL");
return 0;
}
7 лаба==================================================================
1)
const int maxQsize=100;
class Queue
{
char q[maxQsize];
int size;
int putloc, getloc;
public:
Queue(int len)
{
if(len>maxQsize) len= maxQsize;
else if(len <=0) len=1;
size=len;
putloc = getloc = 0;
}
void put(char ch)
{
if(putloc == size)
{
cout<<"Очередь заполненная"<<endl;
return;
}
putloc++;
q[putloc]= ch;
}
char get()
{
if(getloc==putloc)
{
cout<<"Очередь пуста";
return 0;
}
getloc++;
return q[getloc];
}
};
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "Russian");
Queue bigQ(100);
Queue smallQ(4);
char ch;
int i;
cout<<"использование очереди bigQ для хранения алфавита"<<endl;
for(i=0;i<26;i++)
{
bigQ.put('A'+ i);
}
for(i=0;i<26;i++)
{
ch=bigQ.get();
if(ch!=0)cout<<ch;
}
cout<<endl<<endl;
for(i=0;i<5;i++)
{
cout<<"попытка сохранить "<< (char)('Z'-i);
smallQ.put('Z'-i);
cout<<endl;
}
2)
template<typename T>
class MyList
{
public:
MyList();
~MyList();
private:
template<typename T>
class Elem {
public:
Elem *pNext;
T data;
Elem(T data=T(), Elem* pNext = nullptr) {
this -> data = data;
this -> pNext = pNext;
}
};
int Size;
Elem<T> *head;
};
template<typename T>
MyList<T>::MyList()
{
Size = 0;
head = nullptr;
}
template<typename T>
MyList<T>::~MyList()
{
}
template<typename T>
void MyList<T>::push(T data)
{
if (head == nullptr)
{
head = new Elem<T>(data);
}
else
{
Elem<T> *cur = this->head;
while(cur->pNext !=nullptr){
cur = cur->pNext;
}
cur->pNext = new Elem<T>(data);
}
Size++;
}
int main()
{
setlocale(LC_ALL, "ru");
MyList<int> lst;
lst.push(2);
lst.push(5);
lst.push(9);
cout << lst.getSize();
system("pause");
}
8Лаба================================================================================================
1)
class Stack
{
public:
int st[10];
int top;
Stack()
{
top = 0;
}
void push(int var)
{
st[++top] = var;
}
int pop()
{
return st[top--];
}
};
int main()
{
Stack s1;
s1.push(11);
s1.push(22);
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
cout << "3: " << s1.pop() << endl;
cout << "4: " << s1.pop() << endl;
cout << "5: " << s1.pop() << endl;
cout << "6: " << s1.pop() << endl;
return 0;
}
2)
template<class T>
class Stack {
struct node {
T d;
node* next;
node(void) : next(NULL) {}
};
private:
node* ptr;
public:
Stack(void) : ptr(NULL) {}
~Stack() {
this->clear();
}
int main(void) {
Stack<int> st;
// заполняем стек
for (int i = 100; i <= 300; st.push(i++));
class TNB
{
public:
char name[30];
char surname[30];
int country_code;
int number;
};
int main()
{
int n, k, m;
unsigned int i;
TNB client1, client2;
char dano[30];
vector<TNB>object;
for (;;) {
cout << "Welcome to TNB\n";
cout << "(telephone number book)\n\n\n";
cout << "enter <1> for add\n";
cout << "enter <2> for review\n";
cout << "enter <3> for search to name\n";
cout << "enter <4> for search to surname\n";
cout << "enter <5> for search to country code\n";
cout << "enter <6> for serach to number\n";
cout << "enter <7> for delete number\n";
cout << "enter <8> for replace number\n";
cout << "enter <9> for exit\n\n";
cout << "enter <10> for save\n\n";
cout << "enter <11> for open\n\n";
cin >> m;
switch (m)
{
case 1:
{
cout << "enter name\n";
cin >> client1.name;
cout << "\n" << "surname\n";
cin >> client1.surname;
cout << "\n" << "country code\n";
cin >> client1.country_code;
cout << "\n" << "number\n";
cin >> client1.number;
cout << "\n";
object.push_back(client1);
}
case 2:
{
for (i = 0;i < object.size();i++) {
client1 = object[i];
cout << "Name:" << client1.name << "\n";
cout << "Surname:" << client1.surname << "\n";
cout << "Country code:+" << client1.country_code << "\n";
cout << "Number:" << client1.number << "\n";
cout << "\n";
}
_getch();
}break;
case 3:
{
cout << "enter name for search\n";
cin >> dano;
for (i = 0;i < object.size();i++) {
client1 = object[i];
n = strcmp(dano, client1.name);
if (n == 0) {
cout << "Name:" << client1.name << "\n";
cout << "Surname:" << client1.surname << "\n";
cout << "Country code:+" << client1.country_code << "\n";
cout << "Number:" << client1.number << "\n";
}
k = i + 1;
}
if (k == object.size()) cout << "None!\n";
}break;
case 4: {
cout << "enter surname for search\n";
cin >> dano;
for (i = 0; i < object.size(); i++) {
client1 = object[i];
n = strcmp(dano, client1.surname);
if (n == 0) {
cout << "Name:" << client1.name << "\n";
cout << "Surname:" << client1.surname << "\n";
cout << "Country code:+" << client1.country_code << "\n";
cout << "Number:" << client1.number << "\n";
}
k = i + 1;
}
if (k == object.size()) cout << "None!\n";
}break;
case 5:
{
cout << "enter country code\n";
cin >> dano;
char code[4];
int temp;
temp = client1.country_code;
_itoa(temp, code, 10);
break;
case 9:
{
system("pause");
return 0;
}
case 10:
{
ofstream out("d:\\TNB.txt");
out.close();
}
case 11:
{
ifstream file("d:\\TNB.txt");
int n = 255;
char* buffer = new char[n + 1]; buffer[n] = 0;
while (!file.eof())
{
file.read(buffer, n);
cout << buffer;
delete[] buffer;
}
file.close();
cout << endl;
}
}
}
}
Вывод: познакомился с принципами организации многосвязных структур данных и способами их программирования
Лаба10==========================================================
1)
int main()
{
//Реализовать алгоритм поиска простых чисел не превышающих 1000, применив метод генерации исключения для пропуска вывода текущего
числа при обнаружении его первого делителя.
for (int i = 2; i < 1000; i++)
try
{
for (int j = 2; j * j <= i; j++)
{
if (i % j == 0)
break;
else if (j + 1 > sqrt(i)) {
throw i;
}
}
}
catch(int z)
{
cout << z << " ";
}
//Реализовать алгоритм динамического создания целого числа в случае его отсутствия в момент записи нового значения.
int* chisla[30];
for (int i = 0; i < 30; i++)
{
try
{
}
2)
1.
int main()
{
__try
{
setlocale(0, "");
double a, b, c;
int m, n;
cin >> a >> b;
cout << "Выберите действие" << endl;
cout << "1." << "+" << endl;
cout << "2." << "-" << endl;
cout << "3." << "*" << endl;
cout << "4." << "/" << endl;
cin >> m;
switch (m)
{
case 1:
c = a + b;
cout << c << endl;
break;
case 2:
c = a - b;
cout << c << endl;
break;
case 3:
c = a*b;
cout << c << endl;
break;
case 4:
c = a / b;
cout << c << endl;
break;
}
cout << "Преобразовать в целое ?" << endl;
cout << "1." << "yes " << "\t " << "2." << "no" << endl;
cin >> n;
switch (n)
{
case 1:
cout << int(c) << endl;
break;
case 2:
cout << c << endl;
}
}
__except (EXCEPTION_EXECUTE_HANDLER) {
cout << "Error" <<endl;
cout << "Введите правельные значения" << endl;
}
system("pause");
return 0;
}
2.
int main()
{
__try {
srand(time(0));
float **pt = new float*[2]; // 2-е строки
for (int i = 0; i < 2; i++)
pt[i] = new float[5]; // 5 стобцов
}
system("pause");
return 0;
}
Вывод: познакомился с принципами обработки исключительных ситуаций во время выполнения кода программы try \ catch и __try\ __except
методом.
Лаба 12==========================================================
1)
/*
template <typename T>
T sum(T a,T d)
{
return a + d;
}
template <typename T, typename TT>
TT otnim(T a, TT d)
{
return a - d;
}
template <typename T>
T ymnoz(T a, T d)
{
return a * d;
}
template <typename T>
T razdelit(T a, T d)
{
return a / d;
}
int main()
{
cout << sum((char)20, (char)3)<<endl;
cout << otnim(20, (double)3.6) << endl;
cout << ymnoz((float)20, (float)3) << endl;
cout << razdelit((double)20, (double)3) << endl;
}
*/
2)
int main()
{
setlocale(LC_ALL, "rus");
Stack <int> myStack(5);
// заполняем стек
cout << "Заталкиваем элементы в стек: ";
int ct = 0;
while (ct++ != 5)
{
int temp;
cin >> temp;
myStack.push(temp);
}
// конструктор
template <typename T>
Stack<T>::Stack(int s)
{
size = s > 0 ? s : 10; // инициализировать размер стека
stackPtr = new T[size]; // выделить память под стек
top = -1; // значение -1 говорит о том, что стек пуст
}
// деструктор
template <typename T>
Stack<T>::~Stack()
{
delete[] stackPtr; // удаляем стек
}
top++;
stackPtr[top] = value; // помещаем элемент в стек
Вывод: познакомился c методом прототипирования при разработке однообразных участков кода программ.
13Лаба============================================================================
#define PI 3.14159265
class Point
{
public:
double x;
double y;
Point()
{
x = 0;
y = 0;
}
Point(double _x, double _y)
{
x = _x;
y = _x;
}
void show()
{
cout << x << " - X | Y - " << y << endl;
}
void blockPoint(int limitX = 20, int limitY = 20, int centrX = 0, int centrY = 0)
{
//vector
double vX = (x - centrX);
double vY = (y - centrY);
double len = sqrt(vX * vX + vY * vY);
vX /= len;
vY /= len;
double endX = x + vX * 1.4;
double endY = y + vY * 2.8;
//double lenlimX = (limitX - x) / vX;
//double lenlimY = (limitY - y) / vY;
//cout << lenlimX << " " << lenlimY;
cout << endX << " " << endY;
}
};
int main()
{
Point p(5, 5);
p.show();
p.sdvigX(5);
p.show();
p.sdvigY(-2);
p.show();
p.pov(360);
p.show();
cout << p.dist() << endl;
p.show();
p.blockPoint(20, 20);
p.x = 20;
p.y = 20;
p.show();
cout << p.dist() << endl;
Вывод: познакомился c методом создания виртуальных членов данных при проектировании классов и структур данных.
15Лаба=======================================================================
#define PI 3.14159265
class Point
{
public:
double x;
double y;
Point()
{
x = 0;
y = 0;
}
Point(double _x, double _y)
{
x = _x;
y = _x;
}
void show()
{
cout << x << " - X | Y - " << y << endl;
}
void blockPoint(int limitX = 20, int limitY = 20, int centrX = 0, int centrY = 0)
{
//vector
double vX = (x - centrX);
double vY = (y - centrY);
double len = sqrt(vX * vX + vY * vY);
vX /= len;
vY /= len;
double endX = x + vX * 1.4;
double endY = y + vY * 2.8;
//double lenlimX = (limitX - x) / vX;
//double lenlimY = (limitY - y) / vY;
//cout << lenlimX << " " << lenlimY;
cout << endX << " " << endY;
}
};
int main()
{
Point p(5,5);
p.show();
p = p + 4;
p.show();
p = p - 8;
p.show();
p.pov(360);
p.show();
cout << p.dist() << endl;
p.show();
p.blockPoint(20,20);
p.x = 20;
p.y = 20;
p.show();
cout << p.dist() << endl;
}
Вывод: познакомился c методом разработки синтаксиса проектируемых классов данных.