Random Number Between 2 Double Numbers

后端 未结 12 2211
粉色の甜心
粉色の甜心 2020-11-27 10:25

Is it possible to generate a random number between 2 doubles?

Example:

public double GetRandomeNumber(double minimum, double maximum)
{
    return Ra         


        
12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 11:29

    Johnny5 suggested creating an extension method. Here's a more complete code example showing how you could do this:

    public static class RandomExtensions
    {
        public static double NextDouble(
            this Random random,
            double minValue,
            double maxValue)
        {
            return random.NextDouble() * (maxValue - minValue) + minValue;
        }
    }
    

    Now you can call it as if it were a method on the Random class:

    Random random = new Random();
    double value = random.NextDouble(1.23, 5.34);
    

    Note that you should not create lots of new Random objects in a loop because this will make it likely that you get the same value many times in a row. If you need lots of random numbers then create one instance of Random and re-use it.

提交回复
热议问题