using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { public static void Main(string[] args) { Console.WriteLine("Нажмите любую клавишу для продолжения..."); Console.ReadKey(true); double[,] twoD = new double[0, 0]; Random random = new Random(); int i, j; int size = random.Next(1, 5); int newSize = random.Next(1, 5); twoD = new double[size, newSize]; Console.WriteLine("Двумерный массив. Строк: " + size + " .Столбцов: " + newSize); for (i = 0; i < size; i++) for (j = 0; j < newSize; j++) { twoD[i, j] = System.Math.Round(random.NextDouble(), 2, MidpointRounding.ToEven); Console.WriteLine(twoD[i, j]); } Console.ReadKey(true); } } } - The essence of the problem is not very clear - Sublihim
- It is necessary to alter my code into a generalized method - Denis
- It is not clear why we need a generic method if you have an array of a known type. It is also not clear why you initialize twoD at the very beginning. - Oleg Klezovich
- Generalized in what way? What do you want to summarize and for what? - Sublihim
- one@Grundy, yes, the first thing that comes to mind is generics, but there is no reason to use them. Maybe the author understands something else as a generalization? - Sublihim
|
1 answer
Here is a generalized method that displays all elements of a two-dimensional array line by line.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { public static void Main(string[] args) { Console.WriteLine("Нажмите любую клавишу для продолжения..."); Console.ReadKey(true); double[,] twoD = new double[0, 0]; Random random = new Random(); int i, j; int size = random.Next(1, 5); int newSize = random.Next(1, 5); twoD = new double[size, newSize]; Console.WriteLine("Двумерный массив. Строк: " + size + " .Столбцов: " + newSize); for (i = 0; i < size; i++) for (j = 0; j < newSize; j++) { twoD[i, j] = System.Math.Round(random.NextDouble(), 2, MidpointRounding.ToEven); //Console.WriteLine(twoD[i, j]); } PrintArray(twoD); Console.ReadKey(true); } static void PrintArray<T> (T[,] arrayToPrint) { foreach (T a in arrayToPrint) { Console.WriteLine(a.ToString()); } } } } PS Corrected the code so that the method was called without specifying the type of the variable in the array.
- oneand
ref, why? - Grundy - @Grundy agrees to nothing. I just glanced at the book in a quick way, and there in the example with ref, I stuck it without thinking. Thanks for the tip, corrected. - Oleg Klezovich
|