Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: C# Help with Random Command.  (Read 3535 times)

0 Members and 1 Guest are viewing this topic.

hibyy

    Topic Starter


    Rookie

    • Experience: Familiar
    • OS: Windows 8
    C# Help with Random Command.
    « on: May 27, 2009, 02:09:31 PM »
    I went to msdn.com to find a command that would pick a random number for a project I'm working on, but when I read through the command methods It confused me... all I want it to do is pick a random number from 1 - 12 so it's like rolling dice.

    Can I have some help? ???

    cyoung311



      Rookie

      Thanked: 1
      Re: C# Help with Random Command.
      « Reply #1 on: May 27, 2009, 03:10:09 PM »
      A random number generator must always be initialized with a seed.  From then on the number is generated based upon a mathematical formula using the seed value and successive values.  In C# you have two constructs for the Random class.  The first one has no arguments and uses a time value (always different) for a seed.  The second one allows you to specify an int value as a seed.  Easiest to use the first.  Next you retrieve the random number.  In this case the number will be between 0.0 and 1.0.  This means you've got to scale your number from there, so...

              float obj = new Random();
              int random_value = (int) ((obj.Sample() * 11) + 1);

      This was not tested but should fly.

      hibyy

        Topic Starter


        Rookie

        • Experience: Familiar
        • OS: Windows 8
        Re: C# Help with Random Command.
        « Reply #2 on: May 27, 2009, 03:42:17 PM »
        Ok I'll try it thank you!
        (EDIT)
        Nope didn't work for me thank you for trying.
        « Last Edit: May 27, 2009, 04:04:41 PM by hibyy »

        cyoung311



          Rookie

          Thanked: 1
          Re: C# Help with Random Command.
          « Reply #3 on: May 28, 2009, 12:34:10 AM »
          Ooops.  It's simpler than I first explained...

          Random rand = new Random();
          int random_value = rand.Next(1,12);

          That's it.  Instantiate "rand" only once but execute "rand.Next(1,12)" over and over...

          hibyy

            Topic Starter


            Rookie

            • Experience: Familiar
            • OS: Windows 8
            Re: C# Help with Random Command.
            « Reply #4 on: May 29, 2009, 02:24:11 PM »
            Ok I'll try this out thank you for correcting it.  ;D
            (EDIT)
            YAY IT WORKS!!! Thank you Thank you Thank you! (I really needed this!)
            And now I understand the random command too.  ;D