Как заполнить матрицы через рандом - C#

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

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

Как заполнить матрицы через рандом?
Листинг программы
  1. using System;
  2. namespace ConsoleApplication1
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Console.WriteLine("Введите размерность первой матрицы: ");
  9. int[,] A = new int[Convert.ToInt32(Console.ReadLine()), Convert.ToInt32(Console.ReadLine())];
  10. for (int i = 0; i < A.GetLength(0); i++)
  11. {
  12. for (int j = 0; j < A.GetLength(1); j++)
  13. {
  14. Console.Write("A[{0},{1}] = ", i, j);
  15. A[i, j] = Convert.ToInt32(Console.ReadLine());
  16. }
  17. }
  18. Console.WriteLine("Введите размерность второй матрицы: ");
  19. int[,] B = new int[Convert.ToInt32(Console.ReadLine()), Convert.ToInt32(Console.ReadLine())];
  20. for (int i = 0; i < B.GetLength(0); i++)
  21. {
  22. for (int j = 0; j < B.GetLength(1); j++)
  23. {
  24. Console.Write("B[{0},{1}] = ", i, j);
  25. B[i, j] = Convert.ToInt32(Console.ReadLine());
  26. }
  27. }
  28. Console.WriteLine("\nМатрица A:");
  29. Print(A);
  30. Console.WriteLine("\nМатрица B:");
  31. Print(B);
  32. Console.WriteLine("\nМатрица C = A * B:");
  33. int[,] C = Multiplication(A, B);
  34. Print(C);
  35. }
  36. static int[,] Multiplication(int[,] a, int[,] b)
  37. {
  38. if (a.GetLength(1) != b.GetLength(0)) throw new Exception("Матрицы нельзя перемножить");
  39. int[,] r = new int[a.GetLength(0), b.GetLength(1)];
  40. for (int i = 0; i < a.GetLength(0); i++)
  41. {
  42. for (int j = 0; j < b.GetLength(1); j++)
  43. {
  44. for (int k = 0; k < b.GetLength(0); k++)
  45. {
  46. r[i,j] += a[i,k] * b[k,j];
  47. }
  48. }
  49. }
  50. return r;
  51. }
  52. static void Print(int[,] a)
  53. {
  54. for (int i = 0; i < a.GetLength(0); i++)
  55. {
  56. for (int j = 0; j < a.GetLength(1); j++)
  57. {
  58. Console.Write("{0} ", a[i, j]);
  59. }
  60. Console.WriteLine();
  61. }
  62. }
  63. }
  64. }

Решение задачи: «Как заполнить матрицы через рандом»

textual
Листинг программы
  1.         static int[,] CreateMatrix(int lines, int columns)
  2.         {
  3.             var random = new Random();
  4.             var matrix = new int[lines, columns];
  5.             for (int x = 0; x < columns; ++x)
  6.                 for (int y = 0; y < lines; ++y)
  7.                     matrix[y, x] = random.Next(10);
  8.             return matrix;
  9.         }

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


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

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

14   голосов , оценка 4.071 из 5

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

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

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