Generate a random number from 1 to 3 / including 1 decimal place

I can generate a random number between 1 and 3 quite easily.

float x = Random.Range(1, 3);

But I'm trying to create a random number between 1 and 3, including 1 decimal place. that is, 1.0, 1.1, 1.2-2.8, 2.9, 3.0 Any help appreciated. I do not find an easy function for this.

Note. I am using .cs script in Unity

+4
source share
5 answers

You can multiply the result as follows:

float result = rnd.Next(10, 31) * .1f;

This will lead to a range from 1.0to 3.0, step by step .1.

+17
source

It seems solid.

class Program
{
    static void Main(string[] args)
    {
        float fMyNumber = 0;

        Random rnd = new Random(Guid.NewGuid().GetHashCode());
        for (int j = 0; j < 20; j++) {
            fMyNumber = rnd.Next(1, 4);
            fMyNumber += ((float)rnd.Next(10)) / 10;
            Console.WriteLine(fMyNumber.ToString("0.0"));
        }
        Console.ReadLine();
    }
}
0
source

:

Random.Range(1.0, 3.0);
0

, , Random.Range(), float, int. , , , f , . Random.Range(1.0f, 3.0f).

Random.Range , 3.1f 3.0f.

, , , - , .

0

, Unity, System.Random.

:

System.Random rnd = new System.Random();

Unity , .

0

Source: https://habr.com/ru/post/1539472/


All Articles