Где ошибка при вводе 2 массива? - C#

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

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

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

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

textual
Листинг программы
  1. // 1
  2. int[,] array2D_1 = new int[x, y];
  3.  
  4. // 2
  5. int[,] array2D_2 = new int[x, y]; //вот здесь

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


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

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

13   голосов , оценка 3.615 из 5

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

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

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