Как заполнить матрицы через рандом - C#
Формулировка задачи:
Как заполнить матрицы через рандом?
Листинг программы
- using System;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Введите размерность первой матрицы: ");
- int[,] A = new int[Convert.ToInt32(Console.ReadLine()), Convert.ToInt32(Console.ReadLine())];
- for (int i = 0; i < A.GetLength(0); i++)
- {
- for (int j = 0; j < A.GetLength(1); j++)
- {
- Console.Write("A[{0},{1}] = ", i, j);
- A[i, j] = Convert.ToInt32(Console.ReadLine());
- }
- }
- Console.WriteLine("Введите размерность второй матрицы: ");
- int[,] B = new int[Convert.ToInt32(Console.ReadLine()), Convert.ToInt32(Console.ReadLine())];
- for (int i = 0; i < B.GetLength(0); i++)
- {
- for (int j = 0; j < B.GetLength(1); j++)
- {
- Console.Write("B[{0},{1}] = ", i, j);
- B[i, j] = Convert.ToInt32(Console.ReadLine());
- }
- }
- Console.WriteLine("\nМатрица A:");
- Print(A);
- Console.WriteLine("\nМатрица B:");
- Print(B);
- Console.WriteLine("\nМатрица C = A * B:");
- int[,] C = Multiplication(A, B);
- Print(C);
- }
- static int[,] Multiplication(int[,] a, int[,] b)
- {
- if (a.GetLength(1) != b.GetLength(0)) throw new Exception("Матрицы нельзя перемножить");
- int[,] r = new int[a.GetLength(0), b.GetLength(1)];
- for (int i = 0; i < a.GetLength(0); i++)
- {
- for (int j = 0; j < b.GetLength(1); j++)
- {
- for (int k = 0; k < b.GetLength(0); k++)
- {
- r[i,j] += a[i,k] * b[k,j];
- }
- }
- }
- return r;
- }
- static void Print(int[,] a)
- {
- for (int i = 0; i < a.GetLength(0); i++)
- {
- for (int j = 0; j < a.GetLength(1); j++)
- {
- Console.Write("{0} ", a[i, j]);
- }
- Console.WriteLine();
- }
- }
- }
- }
Решение задачи: «Как заполнить матрицы через рандом»
textual
Листинг программы
- static int[,] CreateMatrix(int lines, int columns)
- {
- var random = new Random();
- var matrix = new int[lines, columns];
- for (int x = 0; x < columns; ++x)
- for (int y = 0; y < lines; ++y)
- matrix[y, x] = random.Next(10);
- return matrix;
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д