Solved

# random.nextdouble Problem

Posted on 2012-08-21
178 Views
Hello,

i have this simple class :

``````public ulong generator(byte number)
{

ulong lower = 1;
ulong upper = 1;

for (int i = 1; i < number; i++)
{
lower = lower * 10;
}

upper = lower * 10;

System.Random rand = new Random(DateTime.Now.Millisecond);
return (ulong)(lower + rand.NextDouble() * upper);
}
``````

its getting a number and then it should generator random numbers of the length of the number

example: number is 4 it should make random number of 4 digits long

but some times it get also a 5 digit number why ??

thank you
c-.png
0
Question by:kensy11

LVL 85

Expert Comment

"its getting a number and then it should generator random numbers of the length of the number"

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_27836509.html#a38316897
0

LVL 85

Accepted Solution

Here's a different approach using your original technique, though:
``````        private void button1_Click(object sender, EventArgs e)
{
ulong number = generator(4);
Console.WriteLine(number.ToString());
}

private System.Random rand = new Random();

public ulong generator(byte number)
{
// INCLUSIVE boundaries:
ulong lowerbound = (ulong)Math.Pow(10, number - 1);
ulong upperbound = (ulong)Math.Pow(10, number) - 1;

/*
See: http://msdn.microsoft.com/en-us/library/aa242020(VS.60).aspx
To produce random integers in a given range, use this formula:
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
*/

// Return a number within our lower and upper bound, INCLUSIVE:
return (ulong)((upperbound - lowerbound + 1) * rand.NextDouble() + lowerbound);
}
``````
0

## Featured Post

### Suggested Solutions

C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…