Форум программистов, компьютерный форум, киберфорум
C++ Builder
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 05.12.2013
Сообщений: 20

Нужны комментарии к коду

22.01.2015, 16:34. Показов 591. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Ребят, нужна ваша помощь, я только начинаю учить с++, можете объяснить каждую строчку, пожалуйста, где что то подписано все ранво немного не понятно
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#include <vcl.h>
#include <fstream>
#include <string>
using namespace std;
 
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//максимальное количество
const int LimitPoint   = 100;
const int LimitPoligon = 10;
 
const char *Roz = "::";
// структура координат
struct SMePoint{
    private :
        long int X,Y;
    public :
        SMePoint(){
            this->SetPoint(0, 0);
        };
        SMePoint(int NewX, int NewY){
            this->SetPoint(NewX, NewY);
        };
        void SetPoint(int NewX, int NewY){
            this->X = NewX;
            this->Y = NewY;
        };
        int GetX(void){return this->X;};
        int GetY(void){return this->Y;};
        ~SMePoint(){};
};
//класс - многоугольник
class TMePoligom{
    private :
        SMePoint Points[LimitPoint];
        TImage *Image;
        TColor Color[2];// 0  - полотно
        int CenterX, CenterY, Count;
 
        void AddCount(){this->Count++;};
        int GetValidCount(int pos){
            return (pos > this->GetCount())
                ? this->GetCount()
                : (pos < 0 )
                    ? 0
                    : pos;
        };
 
    public:
        int GetCenterX(void){return this->CenterX;};
        int GetCenterY(void){return this->CenterY;};
        TMePoligom(){this->Refresh();};
 
        void SetCenter(int NewCenterX, int NewCenterY){
            this->CenterX = NewCenterX;
            this->CenterY = NewCenterY;
        };
 
        SMePoint GetPoint(int pos){
            return this->Points[pos];
        }
 
        void SetPoint(SMePoint MePoint, int pos = 0){
            this->Points[pos] = MePoint;
        }
 
        int GetCount(void){return this->Count;};
 
        bool AddPoint(int NewX, int NewY){
            if (this->GetCount() > LimitPoint ) return false;
            SMePoint tmp;
            tmp.SetPoint(NewX, NewY);
            this->SetPoint(tmp, this->GetCount());
            this->AddCount();
            return true;
        };
        //координаты относительно
        int GetValidX(int i){
            return (this->GetCenterX() + this->Points[i].GetX());
        };
        int GetValidY(int i){
            return (this->GetCenterY() - this->Points[i].GetY());
        };
 
        void   SetImage(TImage *NewImage){this->Image = NewImage;};
        TImage *GetImage(void){return this->Image;};
        // сохнанение цветов
        void SetBrushColor(TColor NewColor){this->Color[0] = NewColor;};
        void SetPenColor(TColor NewColor){this->Color[1] = NewColor;}
        TColor GetBrushColor(void){return this->Color[0];};
        TColor GetPenColor(void){return this->Color[1];}
 
        //рисование
        void Draw(){
            int CenterX = this->GetImage()->Width / 2;
            int CenterY = this->GetImage()->Height / 2;
            this->SetCenter(CenterX, CenterY);
            TPoint *tmp = new TPoint[this->GetCount()+1];
            for (int i = 0; i <= this->GetCount(); i++) {
                tmp[i] = Point(this->GetValidX(i % this->GetCount()),
                                              this->GetValidY(i % this->GetCount()));
            };
            this->GetImage()->Canvas->Brush->Color = this->GetBrushColor();
            this->GetImage()->Canvas->Pen->Color   = this->GetPenColor();
            int count_ = this->GetCount();
            this->GetImage()->Canvas->Polygon(tmp, count_);
            delete tmp;
        };
        //загрузка с файла
        void LoadFromFile(string FileName){
                this->Refresh();
            ifstream file;
            file.open(FileName.c_str());
            char *string  = "";
            file.getline(string, 1024);
            file.close();
            this->Clear();
            char * tmp = strtok (string,Roz);
            bool p = false;
            int x = 0, y = 0;
            while (tmp != NULL){
                if (p == false) {
                    x = atoi(tmp);
                }else{
                    y = atoi(tmp);
                    this->AddPoint(x,y);
                };
                p = !p;
                tmp = strtok (NULL, Roz);
            };
            tmp    = "";
            string = "";
        };
        //сохранение
        void SaveToFile(string FileName){
            ofstream file;
            file.open(FileName.c_str(), ios::out);
            for (int i = 0; i < this->GetCount(); i++) {
                file << this->GetPoint(i).GetX() << Roz <<
                                                  this->GetPoint(i).GetY();
                if (i != this->GetCount() - 1 ) file  << Roz;
            }
            file.close();
        }
 
        void Refresh(){this->Count = 0;};
        //очистка канвы
        void Clear(){
            int CenterX = this->GetImage()->Width / 2;
            int CenterY = this->GetImage()->Height / 2;
 
            this->GetImage()->Canvas->Brush->Color = clWhite;
            this->GetImage()->Canvas->Pen->Color   = clBlack;
 
            this->GetImage()->Canvas->Rectangle(0, 0, this->GetImage()
                                               ->Width, this->GetImage()->Height);
 
                this->GetImage()->Canvas->Rectangle(0, CenterY, CenterX * 2, CenterY + 1);
                this->GetImage()->Canvas->Rectangle(CenterX, 0, CenterX + 1, CenterY * 2);
        }
        // сдвиг
        void Landslide(int x = 0, int y = 0){
            try{
                for (int i = 0; i < this->GetCount(); i++) {
        this->Points[i].SetPoint(this->Points[i].GetX() + x, this->Points[i].GetY() +y);
                }
            }catch(...){}
        }
        //отображение
        void Mirrov(){
            for (int i = 0; i < this->GetCount(); i++) {
                this->Points[i].SetPoint(-this->Points[i].GetX(), -this->Points[i].GetY());
            }
        };
};
//структура - массив с обектов
struct SMePoligom{
    private :
        long int Count, CenterX, CenterY;
    public :
 
    int Length;
    TMePoligom Poligoms[LimitPoligon];
    SMePoligom(){this->Length = 0;};
    //добавление нового полинома
    void AddNewPoligom(TComboBox *ComboBox){
        if(this->Count < LimitPoligon){
            ComboBox->Clear();
            this->Poligoms[this->Length++].SetImage(Form1->Image1);
            for (int i = 0; i < this->Length; i++) {
                char *tmp  = "";
                itoa(i+1, tmp, 10);
                ComboBox->Items->Add(tmp);
                tmp ="";
            };
        };
    };
};
//---------------------------------------------------------------------------
int position = 0;
SMePoligom MePoligoms;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner){}
//---------------------------------------------------------------------------
void __fastcall TForm1::Exit1Click(TObject *Sender){
//закрытие формы
    try{
        Form1->Close();
    }catch(...){
        Application->Terminate();
    }
 
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender){
//создание формы
    MePoligoms.AddNewPoligom(Form1->ComboBox1);
    MePoligoms.Poligoms[position].Clear();
    Form1->Timer1->Interval = 75;
    Form1->ColorBox1->ItemIndex = 0;
    Form1->ColorBox2->ItemIndex = 1;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedButton1Click(TObject *Sender){
// читать с файла
    if (Form1->OpenDialog1->Execute()) {
        char *tmp = "";
        tmp = AnsiString(Form1->OpenDialog1->FileName).c_str();
        MePoligoms.Poligoms[position].LoadFromFile(tmp);
        tmp = "";
    }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::SpeedButton2Click(TObject *Sender){
// сохранение в файл
    if (Form1->OpenDialog1->Execute()) {
        char *tmp = "";
        tmp = AnsiString(Form1->OpenDialog1->FileName).c_str();
        MePoligoms.Poligoms[position].SaveToFile(tmp);
        tmp = "";
    }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender){
    if (Form1->ComboBox1->ItemIndex == -1 && Form1->ComboBox1->Items->Count  > 0) {
        Form1->ComboBox1->ItemIndex = 0;
    }
    if (Form1->ColorBox1->ItemIndex < 0) {
        Form1->ColorBox1->ItemIndex = 0;
    }
    if (Form1->ColorBox2->ItemIndex < 0) {
        Form1->ColorBox2->ItemIndex = 1;
    }
    position = Form1->ComboBox1->ItemIndex;
 
}
//---------------------------------------------------------------------------
 
 
void __fastcall TForm1::SpeedButton3Click(TObject *Sender)
{
//создание нового многоугольника
    MePoligoms.AddNewPoligom(Form1->ComboBox1);
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::SpeedButton4Click(TObject *Sender){
//изменение цвета
    TColor Colors[2];
 
    Colors[0] = Form1->ColorBox1->Selected;
    Colors[1] = Form1->ColorBox2->Selected;
 
    MePoligoms.Poligoms[position].SetBrushColor(Colors[0]);
    MePoligoms.Poligoms[position].SetPenColor(Colors[1]);
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::SpeedButton5Click(TObject *Sender){
//отрисовка
    MePoligoms.Poligoms[0].Clear();
    for (int i = 0; i < MePoligoms.Length; i++) {
        MePoligoms.Poligoms[i].Draw();
    }
}
//---------------------------------------------------------------------------
 
 
 
 
void __fastcall TForm1::SpeedButton6Click(TObject *Sender)
{
//сдвиг
    MePoligoms.Poligoms[position].Landslide(atoi(AnsiString(Form1->Edit1->Text).c_str()),
                                                atoi(AnsiString(Form1->Edit2->Text).c_str()));
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::SpeedButton7Click(TObject *Sender){
//отображение
    MePoligoms.Poligoms[position].Mirrov();
}
//---------------------------------------------------------------------------
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
22.01.2015, 16:34
Ответы с готовыми решениями:

Нужны комментарии к коду
#include &lt;vcl.h&gt; //загрузка стандартной библиотеки С++ Билдер #include &lt;math.h&gt; //Заголовочный файл стандартной библиотеки языка...

Нужны комментарии к коду
//--------------------------------------------------------------------------- #include &lt;vcl.h&gt; #pragma hdrstop #include...

Нужны комментарии к коду
Обьясните вот этот код кому не лень: void __fastcall TForm1::Button1Click(TObject *Sender) { String s = RichEdit1-&gt;Text; int...

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
22.01.2015, 16:34
Помогаю со студенческими работами здесь

Комментарии к коду
Доброго времени суток ув. программисты :) Нужны подробные комментарии к каждой строке кода. char res; ...

Дайте комментарии к коду
Здравствуйте. Кто в теме, дайте комментарии к коду #include &lt;vcl.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #pragma...

Комментарии по коду нейронной сети
Доброго времени суток. Задали задание по нейронным сетям, сам в программировании довольно плохо шарю, тем более в теме нейронных сетей. ...

Нужны комментарии к каждой строке кода
Прошу вас помочь.Заранее спасибо TStringList*L=new TStringList; L-&gt;Sorted=true; for(int i=1; i&lt;=Edit1-&gt;Text.Length();i++) ...

Задача 8 ферзей, нужны пояснения к коду
вообщем нашел код рабочий #include&lt;iostream&gt; #include&lt;stdio.h&gt; using namespace std; const int N=8; int X; int...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru