· 6 years ago · Dec 06, 2019, 09:26 AM
1#include "pch.h"
2#include <cstdio>
3#include <cstdlib>
4#include <ctime>
5#include <cmath>
6#include <cerrno>
7#include <conio.h>
8
9using namespace std;
10
11typedef double **table;
12
13int makeTable(table &tab, int rows, int cols);
14/*
15Создает динамический массив указанных размеров
16Входные параметры: rows - количество строчек (положительное число)
17 cols - количество столбцов (положительное число)
18Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
19Возвращает 0 если все хорошо.
20Возвращает 1 если размеры (cols / rows) указаны некорректно.
21*/
22
23int fmakeTable(table &tab, int &rows, int &cols, char *name);
24
25
26void fillTable(table &tab, int rows, int cols, int isRand);
27/*
28Заполняет динамический массив указанных размеров
29Получаемые параметры как у makeTable, + входной isRand
30 isRand должен быть равен или 0, или 1 для того чтобы программа сделала хоть что-то.
31 если isRand == 0, то программа просит пользователя ввести значение в каждую ячейку вручную.
32 если isRand == 1, то программа заполняет массив случайными величинами.
33*/
34
35void outputTable(table &tab, int rows, int cols);
36/*
37Выводит массив на экран
38Получаемые параметры как у makeTable.
39*/
40
41void delTable(table &tab, int &rows, int &cols);
42/*
43Освобождает память из под динамического массива.
44Входных параметров нет.
45Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
46 rows - ссылка на количество строк в этом массиве, при выполнении программы зануляется
47 cols - ссылка на количество столбцов в этом массиве, при выполнении программы зануляется
48*/
49
50void computeTable(table &tab, int rows, int cols, double &result);
51/*
52Вычисляет наименьшую сумму абсолютных величин среди строк, в которых содержится больше всего нулей
53Входные параметры: rows - количество строчек (положительное число)
54 cols - количество столбцов (положительное число)
55Выходные параметры: tab - ссылка на переменную типа table, являющуюся указателем на указатель(2D массивом)
56 result - ссылка на переменную, изменяется программой. Результат
57*/
58
59//void testProg();
60
61
62int main()
63{
64 //testProg();
65
66 table tab;
67 int rows = 0;
68 int cols = 0;
69 char c = 'f';
70 char name[200];
71 FILE *file;
72 bool isFilled = false;
73 bool exists = false;
74 double result = 0;
75 int fr = 0;
76
77 while (c != '8')
78 {
79 if (c == '1')
80 {
81 if (exists)
82 {
83 delTable(tab, rows, cols);
84 isFilled = false;
85 }
86 while (rows <= 0) {
87 printf("Input positive number of rows\n");
88 scanf_s("%d", &rows);
89 }
90 while (cols <= 0) {
91 printf("Input positive number of cols\n");
92 scanf_s("%d", &cols);
93 }
94 makeTable(tab, rows, cols);
95 exists = true;
96 }
97 else if (c == '2')
98 {
99 if (exists)
100 {
101 delTable(tab, rows, cols);
102 }
103 printf("Input name of file, for example \"table1.txt\"\n"\
104 "First two numbers in txt are numbers of ROWS and COLS,\n"\
105 "other numbers will be inputed into the table.\n");
106 //"If there\'s not enough numbers to fill table remaining will become zeros.\n");
107 // 1 = Файл не существует
108 // 2 = недостаточно эллементов
109 // 3 = ошибка при чтении данных
110 // 4 = некорректные значения
111 scanf_s("%s", &name, 200);
112 fr = fmakeTable(tab, rows, cols, name);
113 c = '1';
114 while (fr != 0 && c == '1')
115 {
116 c = 'f';
117 if (fr == 1)
118 printf("Error! Seems that the file doesn't exist.\n");
119 //"1. to try again with other file.\n"\
120 //"2. to return to previous menu.\n");
121 else if (fr == 2)
122 printf("Error! There is not enough elements in a file!\n");
123 else if (fr == 3)
124 printf("Error occured while reading from a file.\n");
125 else if (fr == 4)
126 printf("Error! Inputed sizes are not correct!\n");
127 printf("1. to try again with other file.\n"\
128 "2. to return to previous menu.\n");
129 while (c != '1' && c != '2')
130 c = _getch();
131 if (c == '1')
132 {
133 printf("Input name of file, for example \"table1.txt\"\n"\
134 "First two numbers in txt are numbers of ROWS and COLS,\n"\
135 "other numbers will be inputed into the table.\n");
136 scanf_s("%s", &name, 200);
137 fr = fmakeTable(tab, rows, cols, name);
138 }
139 }
140 if (fr == 0)
141 {
142 exists = true;
143 isFilled = true;
144 }
145 c = 'f';
146 }
147 else if (c == '3')
148 {
149 isFilled = true;
150 fillTable(tab, rows, cols, 0);
151 }
152 else if (c == '4')
153 {
154 isFilled = true;
155 fillTable(tab, rows, cols, 1);
156 }
157 else if (c == '5')
158 {
159 outputTable(tab, rows, cols);
160 }
161 else if (c == '6')
162 {
163 exists = false;
164 isFilled = false;
165 delTable(tab, rows, cols);
166 }
167 else if (c == '7')
168 {
169 computeTable(tab, rows, cols, result);
170 printf("result = %.4lf\n", result);
171 }
172 c = 'f';
173
174 if (!exists)
175 {
176 printf("Table does not exist.\n"\
177 "1. to create new table manually.\n"\
178 "2. to create new table from file.\n"\
179 "3. to exit.\n");
180 while (c != '1' && c != '2' && c != '3')
181 c = _getch();
182 if (c == '3')
183 c = '8';
184 }
185 else
186 {
187 if (!isFilled)
188 {
189 printf("Seems that your table is not filled.\n"\
190 "1. to fill it manually.\n"\
191 "2. to fill it with random values.\n"\
192 "3. to exit.\n");
193 while (c != '1' && c != '2' && c != '3')
194 c = _getch();
195 if (c == '1')
196 c = '3';
197 else if (c == '2')
198 c = '4';
199 else if (c == '3')
200 c = '8';
201 }
202 else
203 {
204 printf("Table exists and filled.\n"\
205 "1. to create a new table.\n"\
206 "2. to create new table from file.\n"\
207 "3. to refill table manually.\n"\
208 "4. to refill table with random values.\n"\
209 "5. to output table.\n"\
210 "6. to delete table.\n"\
211 "7. to compute table.\n"\
212 "8. to exit\n");
213 while (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8')
214 c = _getch();
215 }
216 }
217 //system("cls");
218 }
219
220 if (exists)
221 delTable(tab, rows, cols);
222
223 return 0;
224}
225
226int makeTable(table &tab, int rows, int cols)
227{
228 if (rows > 0 && cols > 0)
229 {
230 tab = new double*[rows];
231 for (int i = 0; i < rows; i++)
232 tab[i] = new double[cols];
233 return 0;
234 }
235 else
236 return 1;
237}
238
239int fmakeTable(table &tab, int &rows, int &cols, char *name)
240{
241 FILE *file;
242 bool flag1 = true, flag2 = true;
243 int val = 0;
244 double dval = 0;
245 errno_t err1, err0 = fopen_s(&file, name, "r");
246 if (err0 != 0)
247 {
248 return 1; // 1 = Файл не существует
249 }
250 else
251 {
252 for (int i = 0; i < 2; i++)
253 {
254 err1 = fscanf_s(file, "%d", &val);
255 if (err1 == EOF) {
256 rows = 0;
257 cols = 0;
258 fclose(file);
259 return 2;
260 } // 2 = недостаточно эллементов
261 else if (err1 != 1) {
262 rows = 0;
263 cols - 0;
264 fclose(file);
265 return 3;
266 } // 3 = ошибка при чтении данных
267 else if (i == 0)
268 rows = val;
269 else
270 cols = val;
271 }
272 if (rows <= 0 || cols <= 0) {
273 rows = 0;
274 cols = 0;
275 fclose(file);
276 return 4; // 4 = некорректные значения
277 }
278 makeTable(tab, rows, cols);
279 for (int i = 0; i < rows; i++)
280 {
281 for (int j = 0; j < cols; j++)
282 {
283 err1 = fscanf_s(file, "%lf", &dval);
284 if (err1 == EOF) {
285 delTable(tab, rows, cols);
286 fclose(file);
287 return 2;
288 } // 2 = недостаточно эллементов
289 else if (err1 != 1) {
290 delTable(tab, rows, cols);
291 fclose(file);
292 return 3;
293 } // 3 = ошибка при чтении данных
294 else
295 tab[i][j] = dval;
296 }
297 }
298 fclose(file);
299 return 0;
300 }
301}
302
303void fillTable(table &tab, int rows, int cols, int isRand)
304{
305 double d;
306 double val;
307 int chncRat;
308 //int chncTen;
309 int sgn;
310 srand(time(0));
311
312 for (int i = 0; i < rows; i++)
313 {
314 for (int j = 0; j < cols; j++)
315 {
316 if (isRand == 1)
317 {
318 d = rand();
319 tab[i][j] = rand();
320 sgn = rand() % 2;
321 chncRat = rand() % 20;
322 if (chncRat > 0)
323 tab[i][j] += d / 876; //RAND_MAX;
324 if (sgn == 1)
325 tab[i][j] *= -1;
326 }
327 else
328 {
329 printf("Table[%d][%d] = ", i, j);
330 scanf_s("%lf", &val);
331 tab[i][j] = val;
332 }
333 }
334 }
335 return;
336}
337
338void outputTable(table &tab, int rows, int cols)
339{
340 for (int i = 0; i < rows; i++)
341 {
342 for (int j = 0; j < cols; j++)
343 {
344 printf("%10.3lf ", tab[i][j]);
345 }
346 putchar('\n');
347 }
348 return;
349}
350
351void delTable(table &tab, int &rows, int &cols)
352{
353 if (rows <= 0 && cols <= 0)
354 {
355 for (int i = 0; i < rows; i++)
356 delete[] tab[i];
357 delete[] tab;
358 rows = 0;
359 cols = 0;
360 return;
361 }
362}
363
364void computeTable(table &tab, int rows, int cols, double &result)
365{
366 int maxzir = -1; // int maxzir = 0; // maxzir (max zeros in row)
367 double minsum = 0; // minsum
368 int zir;
369 double sum;
370 double eps = 1.0e-18;
371
372 //for (int j = 0; j < cols; j++)
373 // minsum += abs(tab[0][j]);
374
375 for (int i = 0; i < rows; i++)
376 {
377 zir = 0;
378 sum = 0;
379
380 for (int j = 0; j < cols; j++)
381 {
382 if (abs(tab[i][j]) < eps)
383 zir += 1;
384 else
385 sum += abs(tab[i][j]);
386 }
387
388 if (zir >= maxzir)
389 {
390 if (zir > maxzir)
391 {
392 maxzir = zir;
393 minsum = sum;
394 }
395 else
396 {
397 if (sum < minsum || minsum == -1)
398 minsum = sum;
399 }
400 }
401 }
402 result = minsum;
403
404 return;
405}
406
407/*
408void testProg()
409{
410 table tab;
411 int rows = 0;
412 int cols = 0;
413 char c = 'f';
414 bool isFilled = false;
415 bool exists = false;
416 double result = 0;
417
418 while (c != '7')
419 {
420 if (c == '1')
421 {
422 c = 'f';
423 if (exists)
424 {
425 delTable(tab, rows, cols);
426 isFilled = false;
427 }
428 while (rows <= 0) {
429 printf("Input positive number of rows\n");
430 scanf_s("%d", &rows);
431 }
432 while (cols <= 0) {
433 printf("Input positive number of cols\n");
434 scanf_s("%d", &cols);
435 }
436 makeTable(tab, rows, cols);
437 exists = true;
438 }
439 else if (c == '2')
440 {
441 c = 'f';
442 isFilled = true;
443 fillTable(tab, rows, cols, 0);
444 }
445 else if (c == '3')
446 {
447 c = 'f';
448 isFilled = true;
449 fillTable(tab, rows, cols, 1);
450 }
451 else if (c == '4')
452 {
453 c = 'f';
454 outputTable(tab, rows, cols);
455 }
456 else if (c == '5')
457 {
458 c = 'f';
459 exists = false;
460 isFilled = false;
461 delTable(tab, rows, cols);
462 }
463 else if (c == '6')
464 {
465 c = 'f';
466 computeTable(tab, rows, cols, result);
467 printf("result = %.4lf\n", result);
468 }
469
470 if (!exists)
471 {
472 printf("Table does not exist.\n"\
473 "1. to create new table.\n"\
474 "2. to exit.\n");
475 while (c != '1' && c != '2')
476 c = _getch();
477 if (c == '2')
478 c = '7';
479 }
480 else
481 {
482 if (!isFilled)
483 {
484 printf("Seems that your table is not filled.\n"\
485 "1. to fill it manually.\n"\
486 "2. to fill it with random values.\n"\
487 "3. to exit.\n");
488 while (c != '1' && c != '2' && c != '3')
489 c = _getch();
490 if (c == '1')
491 c = '2';
492 else if (c == '2')
493 c = '3';
494 else if (c == '3')
495 c = '7';
496 }
497 else
498 {
499 printf("Table exists and filled.\n"
500 "1. to create a new table.\n"\
501 "2. to refill table manually.\n"\
502 "3. to refill table with random values.\n"\
503 "4. to output table.\n"\
504 "5. to delete table.\n"\
505 "6. to compute table.\n"\
506 "7. to exit\n");
507 while (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7')
508 c = _getch();
509 }
510 }
511 system("cls");
512 }
513
514 if (exists)
515 delTable(tab, rows, cols);
516
517 return;
518}
519*/