[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 198

# random.nextdouble Problem

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
kensy11
• 2
1 Solution

Middle School Assistant TeacherCommented:
"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

Middle School Assistant TeacherCommented:
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

• 2
Tackle projects and never again get stuck behind a technical roadblock.