0

Im a beginner in C# I have created this program to generate 7 random numbers at display them in a console. But now I want to generate number with decimals in the range of 18.0-23.5. But I can't figure out how? I have tried with Next.Double but I can't get it to work. Help Please!

Here is my program:

int lotto1 = 0, lotto2 = 0, lotto3 = 0, lotto4 = 0, lotto5 = 0, lotto6 = 0, lotto7 = 0;
Random rnd = new Random();

Console.WriteLine("Din lottorad är:");
lotto1 = rnd.Next(1, 36);
Console.WriteLine("Nr1: " + lotto1);
lotto2 = rnd.Next(1, 36);
Console.WriteLine("Nr2: " + lotto2);
lotto3 = rnd.Next(1, 36);
Console.WriteLine("Nr3: " + lotto3);
lotto4 = rnd.Next(1, 36);
Console.WriteLine("Nr4: " + lotto4);
lotto5 = rnd.Next(1, 36);
Console.WriteLine("Nr5: " + lotto5);
lotto6 = rnd.Next(1, 36);
Console.WriteLine("Nr6: " + lotto6);
lotto7 = rnd.Next(1, 36);
Console.WriteLine("Nr7: " + lotto7);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
user3356636
  • 115
  • 1
  • 11

1 Answers1

8

use NextDouble:

 rnd.NextDouble() * (23.5-18.0) + 18.0

or more generically:

public double NextDouble(Random rnd, double min, double max)
{
    return rnd.NextDouble() * (max-min) + min;
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • You could also make the `NextDouble( Random, double, double )` method into an extension method so it can be used like `rnd.NextDouble( 18.0, 23.5 )`. – Kyle Feb 26 '14 at 16:57
  • To follow up Kyle's suggestion, the method signature would be `public static double NextDouble(this Random rnd, double min, double max)` – Colin DeClue Feb 26 '14 at 20:09