Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
Другие темы раздела
C++ Какие направления C++ перспективны? Интересует, какие направления языка C++ перспективны для будущей работы (понятно, что одним языком не обойтись и еще связки с теми же базами данных, но все-таки...)? Т.е. для будущей работы наиболее перспективно учить Visual Studio, Qt, 1C, ..? https://www.cyberforum.ru/ cpp-beginners/ thread689324.html C++ ООП.Разработать структуру элементов данных класса в виде динамической структуры данных
Здравствуйте, получил задание, но немного недопонимаю как это сделать, с чего начать. Помогите пожалст или объясните образно как сделать, а я уж как-нибудь соображу. Вот задание: Разработать структуру элементов данных класса в виде динамической структуры данных. Разработать конструкторы для различных типов входных данных(без параметров, параметр-строкаб параметр-массив) и деструктор....
C++ Переход на C++ Я программист delphi Я хочу учить язык C++ но не знаю где можно найти видео уроки по Forms Applicaton Помогите плиз https://www.cyberforum.ru/ cpp-beginners/ thread689306.html C++ Продолжение цикла https://www.cyberforum.ru/ cpp-beginners/ thread689305.html
for(h=0; h!=o ;h++){ if(p==k) Всем привет, подскажите что поставить после if чтобы просто продолжить цикл? Мне просто надо сравнить два слова, вот.
C++ Бинарный поиск элемента в массиве
Подскажите пожалуйста, где у меня что не правильно. В комментариях расписал всё что и как. #include <iostream> #include <windows.h> #include <stdio.h> using namespace std; int main() { SetConsoleCP(1251);
C++ Правильное использование конструкторов и деструкторов #include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; class Worker {public: //відкритий доступ Worker(char *, long, float); //оголошення конструктора void show_Worker(void); ~Worker(); //оголошення деструктора private: //закритий доступ https://www.cyberforum.ru/ cpp-beginners/ thread689294.html
C++ Генератор 4-знаковых чисел Добрый день, написал генератор , генерирует числа с 4 знаками. Подскажите , как дописать проверку этих чисел, чтобы все знаки в числе были разные. (1234, но не 1212). Спасибо) # include <iostream> # include <conio.h> #include <ctime> #include <stdlib.h> using namespace std; void main() {srand((unsigned)time(NULL)); https://www.cyberforum.ru/ cpp-beginners/ thread689292.html C++ Вычисление арктангенса
Помогите с задачей. Написал - но не работает, подстажите в чём причины(задание на картинках). Нужно посчитать с помощью суммирования и проверить результаты с эквивалентным выражением при арктангенсе. #include <iostream> #include <cmath> #include <conio.h> using namespace std; const long double PI = 3.1415926535898; int main()
C++ Составить рекурсивную функцию, которая определяет наибольшую цифру, и заменяет все строчные латинские буквы https://www.cyberforum.ru/ cpp-beginners/ thread689285.html
Вообщем снова рекурсия на С++, ну не дружу я с ней:(. Вообщем, смысл задачи: дана строка символов, составить рекурсивную функцию, которая определяет наибольшую цифру, и заменяет этим значением все строчные латинские буквы. Как это без рекурсии сделать знаю. Как рекурсией не понимаю. Так как мало пишу на С++, основной другой язык. Код не обязателен, просто нараотки или идею как это сделать....
C++ Выделение цветом https://www.cyberforum.ru/ cpp-beginners/ thread689277.html
Как в консоли выделить определённые символы другим цветом?
C++ типы переменных
компилятор выдает ошибку Ошибка "error C2062: тип "long" не требуется ". меняю тип но все равно вылезает ошибка только тип другой?
C++ Как узнать свой IP? Интересует именно с помощью boost asio, с последующим выводом на консоль.Ну или как узнать айпишник подключившегося клиента(на стороне сервера)? https://www.cyberforum.ru/ cpp-beginners/ thread689266.html
2 / 2 / 2
Регистрация: 05.07.2012
Сообщений: 99
0

Класс-обработчик должен сортировать список стран выбранного континента по площади и населению - C++ - Ответ 3656199

05.11.2012, 19:21. Показов 661. Ответов 0
Метки (Все метки)

Author24 — интернет-сервис помощи студентам
подскажите где ошибка..

есть 2 класса: страна и континент. Класс-обработчик должен сортировать список стран выбранного континента по площади и населению..

не могу найти ошибку..а программа срочно нужна..помогите

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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
#include<dos.h>
#include<string.h>
#include <iostream>
 
# define one 49
# define two 50
# define three 51
# define four 52
 
#define Col_Count 5
#define Col_Cont 3
 
//using namespace std;
 
int n=Col_Count;
int m=Col_Cont;
 
class Country
{
private:
    char *Name_Country;
    float Naselenije;
    float Ploshad;
    char *Forma_Pravl;
    
public:
    Country();
    ~Country();
    
    char *GetName_Country();
    float GetNaselenije();
    float GetPloshad();
    char *GetForma_Pravl();
        
    void SetName_Country(char *newVal);
    void SetNaselenije(float newVal);
    void SetPloshad(float newVal);
    void SetForma_Pravl(char *newVal);
    
    void Print();
 
};
 
Country::Country()
{
//  printf("Country Constructor without params used\n");
Name_Country=new char[200];
Forma_Pravl=new char[200];
    strcpy(Name_Country,"");
    Naselenije = 0;
    Ploshad = 0;
    strcpy(Forma_Pravl,"");
}
 
Country::~Country()
{
//  printf("Country Destructor used\n");
    if(Name_Country != NULL)
 //  strcpy(Name_Country,"");
 delete[]Name_Country;
    
    if(Forma_Pravl != NULL)
//   strcpy(Forma_Pravl,"");
delete []Forma_Pravl;
}
 
void Country::Print()
{
    printf("%s | %10.2f | %9.2f | %s\n",Name_Country,Naselenije,Ploshad,Forma_Pravl);
}
 
char*Country::GetName_Country()
{   return this->Name_Country ;       }
 
float Country::GetNaselenije()
{   return this->Naselenije;     }
 
float Country::GetPloshad()
{   return this->Ploshad;        }
 
char* Country::GetForma_Pravl()
{   return this->Forma_Pravl;   }
 
void Country::SetName_Country(char *newVal)
{       strcpy(this->Name_Country,newVal);         }
 
void Country::SetNaselenije(float newVal)
{   this->Naselenije = newVal;          }
 
void Country::SetPloshad(float newVal)
{   this->Ploshad = newVal;          }
 
void Country::SetForma_Pravl(char *newVal)
{   strcpy(this->Forma_Pravl,newVal);     }
 
//_______________________________________________________________________
 
class Continent
{
 
private:
    char *Name_Continent;
    Country ListCountries[10];
 
public:
    Country *m_Country;
 
    Continent();
    ~Continent();
    
    char *GetName_Continent ();
    void SetName_Continent (char *newVal);
 
    Country GetListCountries (int i);
    void SetListCountries (char *Name_Country,float Naselenije, char *Forma_Pravl, float Ploshad,int i);
 
    void Create_Country(char* Name, float Plosh, float Nas, char *Form);
    void Delete_Country(char *Name_Country);
 
    void Print_Cont();
};
 
void Continent::Print_Cont()
{
  printf("___________________________________________________________\n");
  printf("%35s\n",Name_Continent);
  printf("___________________________________________________________\n");
  printf("  Name_Country | Naselenije |  Ploshad  | Form_Pravlenija\n");
  printf("___________________________________________________________\n");
  
  for(int i=0;i<n;i++)
  {
  ListCountries[i].Print();
  }
}     
 
Continent::Continent()
{
 //    printf("\n \n Continent Constructor without params used\n\n");
    Name_Continent=new char[256];
    strcpy(this->Name_Continent,"");
}
 
Continent::~Continent()
{
//printf("\nContinent Destructor used\n\n");
    if(this->Name_Continent != NULL)
    //strcpy(this->Name_Continent,"");
    delete []Name_Continent;
}
 
char *Continent::GetName_Continent ()
{    return this->Name_Continent;   }
 
void Continent::SetName_Continent (char *newVal)
{     strcpy(Name_Continent,newVal); }
 
 
Country Continent::GetListCountries (int i)
{   return ListCountries[i]; }
 
void Continent::SetListCountries (char *Name_Country,float Naselenije, char* Forma_Pravl, float Ploshad,int i)
{   
    ListCountries[i].SetName_Country(Name_Country);
    ListCountries[i].SetNaselenije(Naselenije);
    ListCountries[i].SetPloshad(Ploshad);
    ListCountries[i].SetForma_Pravl(Forma_Pravl);         
}
 
void Continent::Create_Country(char *Name, float Plosh, float Nas, char *Form)
{
  ListCountries[n].SetName_Country(Name);
  ListCountries[n].SetPloshad(Plosh);
  ListCountries[n].SetNaselenije(Nas);
  ListCountries[n].SetForma_Pravl(Form);
 
   n+=1;  
}
 
void Continent::Delete_Country(char *Name_Country)
{
int k,k1;
 
for(k=0;k<n;k++)
{
if(strcmp(ListCountries[k].GetName_Country(), Name_Country)==0)
 {
     for(k1=k+1;k<n;k++,k1++)
     {
       if(k1<n){
                ListCountries[k].SetName_Country(ListCountries[k1].GetName_Country());
                ListCountries[k].SetNaselenije(ListCountries[k1].GetNaselenije());
                ListCountries[k].SetPloshad(ListCountries[k1].GetPloshad());
                ListCountries[k].SetForma_Pravl(ListCountries[k1].GetForma_Pravl());
               }     
       else {break;}
     }
      n-=1;
    
 }
}
Print_Cont();
}
//_______________________________________________________________________
 
class Obrabotchik
{
private:
    Continent List_Continents[Col_Cont];
 
public:
    Obrabotchik();
    ~Obrabotchik();
 
    Continent GetListContinents (int i);
    void CreateListContinents();
      
    void Sort_po_plosh(int i);
    void Sort_po_nasel(int i);  
 
};
     
Obrabotchik::Obrabotchik()
{
// printf("\n \n Obr Constructor without params used\n\n");
}
 
Obrabotchik::~Obrabotchik()
{
//printf("\nObr Destructor used\n\n");
}
 
 
Continent Obrabotchik::GetListContinents (int i)
{   return List_Continents[i];   }
 
void Obrabotchik::CreateListContinents()
{
 int i,j;
char c[20]={"Name_Continent_"},name[15]={"Name_Country_"},form[15]={"Form_Country_"},str[30],str1[30];
float x1,x2;
 
     for( i=0;i<Col_Cont;i++)
     {
     sprintf(str, "%s %d",c, i+1);
     List_Continents[i].SetName_Continent(str);
     
        for(j=0;j<Col_Count;j++)
       {
          sprintf(str, "%s %d",name, j+1);
          sprintf(str1, "%s %d",form, j+1);  
          x1=(float)200+rand()/300;                                                 
          x2=(float)200+rand()/300;                                                 
          List_Continents[i].SetListCountries(str,x1,str1,x2,j);
       }
       List_Continents[i].Print_Cont();
     }
}
 
void Obrabotchik::Sort_po_plosh(int k)
{
int i,j,imin=0;
 
float min_el=99000;
 
Country temp;
 
for(i=0;i<Col_Count;i++)
{
  imin=i;
  min_el=List_Continents[k].GetListCountries(i).GetPloshad();
  
  for(j=i+1;j<Col_Count;j++)
  {
    if(List_Continents[k].GetListCountries(j).GetPloshad()<min_el){
              imin=j;
              min_el=List_Continents[k].GetListCountries(j).GetPloshad();
            } 
  }
  
  temp.SetName_Country(List_Continents[k].GetListCountries(i).GetName_Country());
  temp.SetForma_Pravl(List_Continents[k].GetListCountries(i).GetForma_Pravl());
  temp.SetNaselenije(List_Continents[k].GetListCountries(i).GetNaselenije());
  temp.SetPloshad(List_Continents[k].GetListCountries(i).GetPloshad());
  
  List_Continents[k].SetListCountries(List_Continents[k].GetListCountries(imin).GetName_Country(),List_Continents[k].GetListCountries(imin).GetNaselenije(),List_Continents[k].GetListCountries(imin).GetForma_Pravl(),List_Continents[k].GetListCountries(imin).GetPloshad(),i);
 
  List_Continents[k].SetListCountries(temp.GetName_Country(),temp.GetNaselenije(),temp.GetForma_Pravl(),temp.GetPloshad(),imin);
   
}
}
     
void Obrabotchik::Sort_po_nasel(int k)
{
int i,j,imin=0;
 
float min_el=99000;
 
Country temp;
 
for(i=0;i<Col_Count-1;i++)
{
  imin=i;
  min_el=List_Continents[k].GetListCountries(i).GetNaselenije();
  
  for(j=i+1;j<Col_Count;j++)
  {
    if(List_Continents[k].GetListCountries(j).GetNaselenije()<min_el){
                                                                      imin=j;
                                                                      min_el=List_Continents[k].GetListCountries(j).GetNaselenije();
                                                                     } 
  }
  
  temp.SetName_Country(List_Continents[k].GetListCountries(i).GetName_Country());
  temp.SetForma_Pravl(List_Continents[k].GetListCountries(i).GetForma_Pravl());
  temp.SetNaselenije(List_Continents[k].GetListCountries(i).GetNaselenije());
  temp.SetPloshad(List_Continents[k].GetListCountries(i).GetPloshad());
  
  List_Continents[k].SetListCountries(List_Continents[k].GetListCountries(imin).GetName_Country(),List_Continents[k].GetListCountries(imin).GetNaselenije(),List_Continents[k].GetListCountries(imin).GetForma_Pravl(),List_Continents[k].GetListCountries(imin).GetPloshad(),i);
 
  List_Continents[k].SetListCountries(temp.GetName_Country(),temp.GetNaselenije(),temp.GetForma_Pravl(),temp.GetPloshad(),imin);
   
}
}
 
 
int main()
{
    {
    
     int i;
     char *a,*f;
     float s=12,p=32;
 
 a=new char [200];
 f=new char [200];
 strcpy(a,"Name_Country_ 1");
 strcpy(f,"Form");
 
     Obrabotchik A;
     A.CreateListContinents();
/*
for(i=0;i<n;i++)
A.GetListContinents(i).Print_Cont();
 */
A.GetListContinents(0).Delete_Country(a);
 
//A.GetListContinents(0).Create_Country(a,s,p,f);
 
for(i=0;i<m;i++)
A.GetListContinents(i).Print_Cont();
 
    }
    system("pause");
    return 0;
}


Вернуться к обсуждению:
Класс-обработчик должен сортировать список стран выбранного континента по площади и населению C++
0
Заказать работу у эксперта
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
05.11.2012, 19:21
Готовые ответы и решения:

Класс-обработчик должен вывести список клиентов, которые имеют задолженности по погашению кредитов
Доброй ночи) Кто может помочь с заданием у меня не получается разобраться с классом-обработчиком

Дан список стран с указанием занимаемой площади и численности населения. Вывести названия стран с максимальной площадью
Решить задачу по обработке записей: Дан список стран с указанием занимаемой площади и численности...

Список стран должен возвращаться из WCF вэб сервиса при помощи AJAX запроса
Список стран должен возвращаться из WCF вэб сервиса при помощи AJAX запроса. Вот такая строчка...

Список городов по населению
Стоит задача: получить список всех городов Росии с населением более 100 т. человек. Если...

0
05.11.2012, 19:21
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
05.11.2012, 19:21
Помогаю со студенческими работами здесь

Список стран и список столиц этих стран
Составить нерекурсивную программу в форме λ-вызова, откомпилировать и выполнить на SECD-машине....

Определить средние значения площади стран и их населения для каждого полушария Земли
Создать электронную таблицу3 MS Excel. Определить средние значения площади стран и их населения для...

std::sort. Как сортировать список? (список указателей на объект)
Всем доброго времени суток! Извините за флуд темами, я не специально С простыми типами то всё...

Описать абстрактный класс породить от него еще два,один должен остаться абстрактным,другой должен быть способен пораждать объекты
Знает кто как сделать?

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru