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