miércoles, 3 de diciembre de 2014

C# - How to generate random numbers



Hi!
In this chapter I’m going to describe how to generate random numbers in C#. There are different ways to do this:
1.- Specifying INCLUSIVE Minimum and EXCLUSIVE Maximum values.
2- Specifying EXCLUSIVE Maximum value, which generates a number between “0” INCLUDED and Maximum value EXCLUDED
3.- No value in the overload constructor. This generates random integer numbers
Check the example code below:


private void button2_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            Console.WriteLine("Generate 10 random numbers with Min and Max values specified");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(r.Next(1, 11).ToString());
            }
            Console.WriteLine("\nGenerate 10 random numbers with only Max value specified");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(r.Next(11).ToString());
            }
            Console.WriteLine("\nGenerate 10 random integer numbers");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(r.Next().ToString());
            }  
        }

Output in console box:

Generate 10 random numbers with Min and Max values specified
7
2
7
4
1
7
6
4
7
6

Generate 10 random numbers with only Max value specified
2
6
2
0
9
9
0
5
7
2

Generate 10 random integer numbers
1965436513
1588247958
1972778565
1559062891
651004989
2090314014
1471196922
624391393
1358340024
2110723804

No hay comentarios.:

Publicar un comentario