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

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

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);
        }

Open in new window


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
Asked:
kensy11
  • 2
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
"its getting a number and then it should generator random numbers of the length of the number"

See my comments in your PAQ:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_27836509.html#a38316897
0
 
Mike TomlinsonMiddle 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);
        }

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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