Где ошибка при самостоятельном вводе массива? - C#

Узнай цену своей работы

Формулировка задачи:

Добрый вечер. Не судите строго. Кучу раз уже пришлось переделать...Поэтому мозги кипят) Подскажите пожалуйста не могу разобраться, где допускаю ошибку при самостоятельном вводе массива?И как можно сделать работу более "красивой"?
Листинг программы
  1. /*
  2. Алгоритмы работы с многомерными массивами
  3. (матрицы, кубы и т.д., срезы многомерных массивов, сложение,
  4. разность, умножение матриц, нахождение обратной матрицы,
  5. определителя для матриц произвольной размерности)
  6. */
  7. class Program
  8. {
  9. // Динамическое сложение
  10. private static T Add<T>(T t1, T t2)
  11. {
  12. dynamic a = t1;
  13. dynamic b = t2;
  14. return a + b;
  15. }
  16. // Динамическая разность
  17. private static T Sub<T>(T t1, T t2)
  18. {
  19. dynamic a = t1;
  20. dynamic b = t2;
  21. return a - b;
  22. }
  23. // Динамическое умножение
  24. private static T Mult<T>(T t1, T t2)
  25. {
  26. dynamic a = t1;
  27. dynamic b = t2;
  28. return a * b;
  29. }
  30.  
  31. // Динамическое деление
  32. private static T Division<T>(T t1, T t2)
  33. {
  34. dynamic a = t1;
  35. dynamic b = t2;
  36. return a / b;
  37. }
  38. // Конвертация массива в простейший JSON
  39. public static string ArrToBasicJSON<T>(T[] arr)
  40. {
  41. string str = "";
  42. str += "[";
  43. for (int x = 0, lenX = arr.GetLength(0); x < lenX; x++)
  44. {
  45. if (x > 0) { str += ", "; };
  46. str += arr[x].ToString();
  47. }
  48. str += "]";
  49. return str;
  50. }
  51. public static string Arr2DToBasicJSON<T>(T[,] arr)
  52. {
  53. string str = "";
  54. for (int x = 0, lenX = arr.GetLength(0); x < lenX; x++)
  55. {
  56. if (x > 0) { str += ", \n"; };
  57. str += "[";
  58. for (int y = 0, lenY = arr.GetLength(1); y < lenY; y++)
  59. {
  60. if (y > 0) { str += ", "; };
  61. str += arr[x, y].ToString();
  62. }
  63. str += "]";
  64. }
  65. return str;
  66. }
  67. // Срез массива
  68. public static T[] Slice<T>(T[] source, int start, int end)
  69. {
  70. int count;
  71. count = end - start;
  72. T[] target = null;
  73. if (count > 0)
  74. {
  75. target = new T[count];
  76. for (int i = start; i < end; i++)
  77. {
  78. target[i - start] = source[i];
  79. }
  80. }
  81. return target;
  82. }
  83. // Срез двумерного массива
  84. public static T[,] Slice2D<T>(T[,] source, int startY, int endY, int startX, int endX)
  85. {
  86. int countX;
  87. int countY;
  88. countX = endX - startX;
  89. countY = endY - startY;
  90. T[,] target = new T[countX, countY];
  91. for (int x = 0; x < countX; x++)
  92. {
  93. for (int y = 0; y < countY; y++)
  94. {
  95. target[x, y] = source[x + startY, y + startX];
  96. }
  97. }
  98. return target;
  99. }
  100. // Сумма матриц
  101. public static T[,] Add2D<T>(T[,] arr_1, T[,] arr_2)
  102. {
  103. int lenX_1, lenX_2, lenX_max;
  104. int lenY_1, lenY_2, lenY_max;
  105. lenX_1 = arr_1.GetLength(0);
  106. lenY_1 = arr_1.GetLength(1);
  107. lenX_2 = arr_2.GetLength(0);
  108. lenY_2 = arr_2.GetLength(1);
  109. lenX_max = Math.Max(lenX_1, lenX_2);
  110. lenY_max = Math.Max(lenY_1, lenY_2);
  111. T[,] target = new T[lenX_max, lenY_max];
  112. for (int x = 0; x < lenX_max; x++)
  113. {
  114. for (int y = 0; y < lenY_max; y++)
  115. {
  116. if (x < lenX_1 && y < lenY_1)
  117. {
  118. T item_1 = arr_1[x, y];
  119. // Замена нулей
  120. target[x, y] = Add<T>(target[x, y], item_1);
  121. }
  122. if (x < lenX_2 && y < lenY_2)
  123. {
  124. T item_2 = arr_2[x, y];
  125. target[x, y] = Add<T>(target[x, y], item_2);
  126. }
  127. }
  128. }
  129. return target;
  130. }
  131. // Разность матриц
  132. public static T[,] Sub2D<T>(T[,] arr_1, T[,] arr_2)
  133. {
  134. int lenX_1, lenX_2, lenX_max;
  135. int lenY_1, lenY_2, lenY_max;
  136. lenX_1 = arr_1.GetLength(0);
  137. lenY_1 = arr_1.GetLength(1);
  138. lenX_2 = arr_2.GetLength(0);
  139. lenY_2 = arr_2.GetLength(1);
  140. lenX_max = Math.Max(lenX_1, lenX_2);
  141. lenY_max = Math.Max(lenY_1, lenY_2);
  142. T[,] target = new T[lenX_max, lenY_max];
  143. for (int x = 0; x < lenX_max; x++)
  144. {
  145. for (int y = 0; y < lenY_max; y++)
  146. {
  147. if (x < lenX_1 && y < lenY_1)
  148. {
  149. T item_1 = arr_1[x, y];
  150. // Замена нулей
  151. target[x, y] = Add<T>(target[x, y], item_1);
  152. }
  153. if (x < lenX_2 && y < lenY_2)
  154. {
  155. T item_2 = arr_2[x, y];
  156. target[x, y] = Sub<T>(target[x, y], item_2);
  157. }
  158. }
  159. }
  160. return target;
  161. }
  162. // Умножение матриц
  163. public static T[,] Mult2D<T>(T[,] arr_1, T[,] arr_2)
  164. {
  165. int lenX_1, lenX_2;
  166. int lenY_1, lenY_2;
  167. lenX_1 = arr_1.GetLength(0);
  168. lenY_1 = arr_1.GetLength(1);
  169. lenX_2 = arr_2.GetLength(0);
  170. lenY_2 = arr_2.GetLength(1);
  171. // Проверка на допустимость операции
  172. if (lenY_1 != lenX_2)
  173. {
  174. throw new System.InvalidOperationException("Нельза умножать несогласованные матрицы.");
  175. }
  176. T[,] target = new T[lenX_1, lenY_2];
  177. for (int k = 0; k < lenY_2; k++)
  178. {
  179. for (int i = 0; i < lenX_1; i++)
  180. {
  181. for (int j = 0; j < lenX_2; j++)
  182. {
  183. T item_1 = arr_1[i, j];
  184. T item_2 = arr_2[j, k];
  185. target[i, k] = Add<T>(target[i, k], Mult<T>(item_1, item_2));
  186. }
  187. }
  188. }
  189. return target;
  190. }
  191. // Транспонирование матрицы
  192. public static T[,] Trans<T>(T[,] arr)
  193. {
  194. int lenX = arr.GetLength(0);
  195. int lenY = arr.GetLength(1);
  196. T[,] target = new T[lenY, lenX];
  197. for (int i = 0; i < lenX; i++)
  198. {
  199. for (int j = 0; j < lenY; j++)
  200. {
  201. target[j, i] = arr[i, j];
  202. }
  203. }
  204. return target;
  205. }
  206. // Определитель матрицы
  207. // public static T Determinant<T>(T[,] arr){
  208. // int N = arr.GetLength(0);
  209. // dynamic denom = 1;
  210. // int exchanges = 0;
  211. //
  212. // dynamic target = Trans<T>(arr);
  213. //
  214. // for (int i = 0; i < N-1; i++){
  215. // dynamic maxN = i;
  216. // dynamic maxValue = Math.Abs(target[i, i]);
  217. //
  218. // for (dynamic j = i + 1; j < N; j++){
  219. // dynamic value = Math.Abs(target[j, i]);
  220. //
  221. // if (value > maxValue){
  222. // maxN = j;
  223. // maxValue = value;
  224. // }
  225. // }
  226. //
  227. // if (maxN > i){
  228. // dynamic temp = target[i];
  229. // target[i] = target[maxN];
  230. // target[maxN] = temp;
  231. //
  232. // exchanges++;
  233. // } else {
  234. // if (maxValue == 0){
  235. // return maxValue;
  236. // }
  237. // }
  238. //
  239. // dynamic value1 = target[i, i];
  240. // for (int j = i + 1; j < N; j++){
  241. // dynamic value2 = target[j, i];
  242. // target[j, i] = 0;
  243. //
  244. // for (int k = i + 1; k < N; k++){
  245. // target[j, k] = (target[j, k] * value1 - target[i, k] * value2) / denom;
  246. // }
  247. // }
  248. //
  249. // denom = value1;
  250. // }
  251. //
  252. // if (exchanges % 2 == 0){
  253. // return -target[N-1, N-1];
  254. // } else {
  255. // return target[N-1, N-1];
  256. // }
  257. // }
  258. // Определитель матрицы 2 x 2
  259. public static int Determinant2(int[,] x1)
  260. {
  261. int md2 = x1[0, 0] * x1[1, 1]
  262. - x1[1, 0] * x1[0, 1];
  263. return md2;
  264. }
  265. // Определитель матрицы 3 x 3
  266. public static int Determinant3(int[,] x1)
  267. {
  268. int md3 = x1[0, 0] * x1[1, 1] * x1[2, 2]
  269. + x1[2, 0] * x1[0, 1] * x1[1, 2]
  270. + x1[1, 0] * x1[2, 1] * x1[0, 2]
  271. - x1[2, 0] * x1[1, 1] * x1[0, 2]
  272. - x1[0, 0] * x1[2, 1] * x1[1, 2]
  273. - x1[1, 0] * x1[0, 1] * x1[2, 2];
  274. return md3;
  275. }
  276. public static bool Str_to_bool(string str)
  277. {
  278. bool ans = false;
  279. switch (str)
  280. {
  281. case "y":
  282. case "Y":
  283. case "yes":
  284. case "Yes":
  285. case "д":
  286. case "Д":
  287. case "да":
  288. case "Да":
  289. ans = true;
  290. break;
  291. default:
  292. ans = false;
  293. break;
  294. }
  295. return ans;
  296. }
  297. static void Main()
  298. {
  299. Console.WriteLine("Введите размерность массива: ");
  300. Console.WriteLine("x: ");
  301. int x = Convert.ToInt32(Console.ReadLine());
  302. Console.WriteLine("y: ");
  303. int y = Convert.ToInt32(Console.ReadLine());
  304. Console.WriteLine("нужен ли второй массив? y/n: ");
  305. bool has_seccond_arr = Str_to_bool(Console.ReadLine());
  306. Console.WriteLine("желаете воодить сами (n) или ввести случайные значения (y)? y/n: ");
  307. bool is_auto_fill = Str_to_bool(Console.ReadLine());
  308. // 1
  309. int[,] array2D_1 = new int[x, y];
  310. // 2
  311. int[,] array2D_2 = new int[x, y];
  312. if (is_auto_fill)
  313. {
  314. Random random = new Random();
  315. for (int c_x = 0; c_x < x; c_x++)
  316. {
  317. for (int c_y = 0; c_y < x; c_y++)
  318. {
  319. array2D_1[c_x, c_y] = random.Next(-42, 42);
  320. if (has_seccond_arr)
  321. {
  322. array2D_2[c_x, c_y] = random.Next(-42, 42);
  323. }
  324. }
  325. }
  326. }
  327. else
  328. {
  329. Console.WriteLine("Первый массив");
  330. for (int c_x = 0; c_x < x; c_x++)
  331. {
  332. for (int c_y = 0; c_y < x; c_y++)
  333. {
  334. array2D_1[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
  335. }
  336. }
  337. Console.WriteLine("Второй массив");
  338. for (int c_x = 0; c_x < x; c_x++)
  339. {
  340. for (int c_y = 0; c_y < x; c_y++)
  341. {
  342. array2D_2[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
  343. }
  344. }
  345. }
  346. Console.WriteLine("\n\n");
  347. Console.WriteLine("Первый массив");
  348. Console.WriteLine(Arr2DToBasicJSON(array2D_1));
  349. Console.WriteLine("Второй массив");
  350. Console.WriteLine(Arr2DToBasicJSON(array2D_2));
  351. Console.WriteLine("\n\n");
  352. Console.WriteLine("Выбирите операцию:");
  353. Console.WriteLine(
  354. " 1) Срез двумерного массива \n"
  355. + " 2) Сложение матриц \n"
  356. + " 3) Разность матриц \n"
  357. + " 4) Умножение матриц \n"
  358. + " 5) Транспонирование матрицы \n"
  359. + " 6) Определитель матрицы 2 x 2 \n"
  360. + " 7) Определитель матрицы 3 x 3 \n"
  361. );
  362. int variant = Convert.ToInt32(Console.ReadLine());
  363. switch (variant)
  364. {
  365. // Срез двумерного массива
  366. case 1:
  367. Console.WriteLine("Введите начала среза по Y:");
  368. int slice_y_start = Convert.ToInt32(Console.ReadLine());
  369. Console.WriteLine("Введите конец среза по Y:");
  370. int slice_y_end = Convert.ToInt32(Console.ReadLine());
  371. Console.WriteLine("Введите начала среза по X:");
  372. int slice_x_start = Convert.ToInt32(Console.ReadLine());
  373. Console.WriteLine("Введите конец среза по X:");
  374. int slice_x_end = Convert.ToInt32(Console.ReadLine());
  375. array2D_1 = Slice2D(
  376. array2D_1
  377. , slice_y_start
  378. , slice_y_end
  379. , slice_x_start
  380. , slice_x_end
  381. );
  382. Console.WriteLine(Arr2DToBasicJSON(array2D_1));
  383. break;
  384. // Сложение матриц
  385. case 2:
  386. Console.WriteLine(Arr2DToBasicJSON(Add2D(array2D_1, array2D_2)));
  387. break;
  388. // Разность матриц
  389. case 3:
  390. Console.WriteLine(Arr2DToBasicJSON(Sub2D(array2D_1, array2D_2)));
  391. break;
  392. // Умножение матриц
  393. case 4:
  394. Console.WriteLine(Arr2DToBasicJSON(Mult2D(array2D_1, array2D_2)));
  395. break;
  396. // Транспонирование матрицы
  397. case 5:
  398. Console.WriteLine(Arr2DToBasicJSON(Trans(array2D_1)));
  399. break;
  400. // Определитель матрицы 2 x 2
  401. case 6:
  402. Console.WriteLine(Determinant2(array2D_1));
  403. break;
  404. // Определитель матрицы 3 x 3
  405. case 7:
  406. default:
  407. Console.WriteLine(Determinant3(array2D_1));
  408. break;
  409. }
  410. Console.ReadLine();
  411. }
  412. }

Решение задачи: «Где ошибка при самостоятельном вводе массива?»

textual
Листинг программы
  1. else
  2.             {
  3.                 Console.WriteLine(has_seccond_arr ? "Первый массив" : "Введите элементы массива");
  4.                 for (int c_x = 0; c_x < x; c_x++)
  5.                 {
  6.                     for (int c_y = 0; c_y < y; c_y++)
  7.                     {
  8.                         array2D_1[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
  9.                     }
  10.                 }
  11.                 if (has_seccond_arr)
  12.                 {
  13.                     Console.WriteLine("Второй массив");
  14.                     for (int c_x = 0; c_x < x; c_x++)
  15.                     {
  16.                         for (int c_y = 0; c_y < y; c_y++)
  17.                         {
  18.                             array2D_2[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
  19.                         }
  20.                     }
  21.                 }
  22.             }
  23.  
  24.             Console.WriteLine("\n\n");
  25.             Console.WriteLine(has_seccond_arr ? "Первый массив" : "Массив");
  26.             Console.WriteLine(Arr2DToBasicJSON(array2D_1));
  27.             if (has_seccond_arr)
  28.             {
  29.                 Console.WriteLine("Второй массив");
  30.                 Console.WriteLine(Arr2DToBasicJSON(array2D_2));
  31.             }
  32.             Console.WriteLine("\n\n");
  33.  
  34.             Console.WriteLine("Выберите операцию:");

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

7   голосов , оценка 4.143 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы