Random?

How can I do random from x to y ? From 0 to 20 lets say ?
brightwoodAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
x + std::rand() % (y-x+1);
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
brightwoodAuthor Commented:
mm, im looking for something like

double result = random (min,max)

and then convert result cu CString.

Also, for  std::rand() don't i have to include something ?
0
ozoCommented:
#include <cstdlib>
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

jkrCommented:
Adding to ozo's explanation of the basics, you could use

#include <stdlib.h>

#include <time.h>

class Random {

public:

    Random() {srand( (unsigned)time( NULL ) );}

    double random(double min, double max) const {
   
        double dRand = (double) rand () / (double) RAND_MAX;

        double dResult = dRand * (dMax - dMin) + dMin;

        return dResult;
    }

};

//...

Random r;

double result = r.random (min,max);

You could have that also be

double random(double min, double max) const {

    double dRand = (double) rand () / (double) RAND_MAX;

    double dResult = dRand * (dMax - dMin) + dMin;

    return dResult;
}

//...
double result = random (min,max);

without a class, but you'd have to be sure to seed the random number generator 'manually'.
0
List244Commented:
Also, just to note, if you use #include <iostream> you do not need to include stdlib
0
ApplicationmakerCommented:
I created an own function called rand.
this function can use min and max.
The standard function from the my Borland compiler has only an maximum to use.
Do you want also random values like 3042.492 or so?


//---------------------------------------------------------------------------

#include <vcl.h>
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
#pragma hdrstop

double rand(int Min,int Max);

//---------------------------------------------------------------------------

double rand(int Min,int Max) {
      int Result;
      Result=random(Max);
      while(Result <=Min){
            Result=random(Max);
      }
      return Result;
}

#pragma argsused
int main(int argc, char* argv[])
{
      double RandomNumber,Min, Max;

      cout <<"Random Numbers!:";
      cout <<"\nMin";cin >>Min;
      cout <<"\nMax";cin >>Max;
      randomize();
      cout <<"\n\nResults:\n";
      for(int i=0;i<20;i++){
            RandomNumber=rand(Min,Max);
            cout <<"\n"<<RandomNumber;
      }
      getch();
      return 0;
}
//---------------------------------------------------------------------------
0
pcgabeCommented:
OK, first a function to return a random number in a given range:

Firstly, these require:
#include <time.h>      //used to seed the random-number generator

You'd need the standard library for rand(), but if you're using CStrings, you're using MFC, so you don't need to explicitly #include it.

Now, on to the function!

int random(int min, int max)
{
      static bool firstrun=true;      //Is this the first call to this function?
      if (firstrun)      //if so...
      {
            //When called the first time, seeds the random-number
            //generator with the current time so that the numbers will
            //be different each time you run it.
               srand( (unsigned)time( NULL ) );      
               firstrun=false;      //don't call this again
      }
      //This looks more complicated than it is.  ^_^
      int range = max - min + 1;      //sets the size of your range PLUS ONE (important)
      return int(min + ( range * rand() / (RAND_MAX + 1.0) ));
      /* The explanation:
      The variable "range" is the size of the range you are using.
      For example, if min=5 and max=10, range==6 (eg, 10-5+1)

      rand() / (RAND_MAX + 1.0) gives you a random value between [0..1)
      That is to say, somewhere between 0.0 and up to (but not including) 1.0

      When we multiply that by our range, in this case we get a
      random value between [0..6)

      Lastly, we add our minimum value, leaving us with a final random
      value between [5..11)

      If we convert this to an int, everything past the decimal point is
      chopped off, leaving us      with an integer value between [5..10],
      inclusive.  If you DON'T want to convert to int, change the range
      so that it does not add one.
      */
}

For doubles, here's the same function (sans comments)

double drandom(double min, double max)
{
      static bool firstrun=true;
      if (firstrun)
      {
               srand( (unsigned)time( NULL ) );      
               firstrun=false;
      }
      double range = max - min;
      return (min + ( range * rand() / (RAND_MAX + 1.0) ));
}


Now, as to converting to a CString, it's super easy.  ^_^

CString has a built-in function called Format, and it works just like printf.

So, given a CString str, to convert an int, just use:

str.Format("%d",blah); where blah is the int.  For example:

str.Format("%d",random(10,20));
(This sets the CString str to an integer value between 10 and 20)

If you would rather use floating random numbers, simply change your format string to reflect that:

str.Format("%.2f",drandom(10,20));
(Sets str to a value between 10 and 20 with two digits of precision)
0
PaneQCommented:
Applicationmaker wrote:

double rand(int Min,int Max) {
     int Result;
     Result=random(Max);
     while(Result <=Min){
          Result=random(Max);
     }
     return Result;
}

LOL. That is very unoptimalizated funcation. Which school teachs to write like this ?
That's why some applications are really slow...
0
seet82Commented:
[QUOTE]
Applicationmaker wrote:

double rand(int Min,int Max) {
     int Result;
     Result=random(Max);
     while(Result <=Min){
          Result=random(Max);
     }
     return Result;
}

LOL. That is very unoptimalizated funcation. Which school teachs to write like this ?
That's why some applications are really slow...
[/QUOTE]

let's try this function
rand(99999,100000);
see how many long the while loop runs
0
pcgabeCommented:
I have an objection.  Neither ozo's nor jkr's comments explain anything, nor do they completely answer the author's questions.  Mine was the only post to answer (and explain the why and how) the random range function and the conversion to cstring.  If you have to split, split between me and jkr.
0
VenabiliCommented:
The original question is how to geneate a random number and both answers answer it fully
0
pcgabeCommented:
Humbly, I disagree.  As I understood it, our role is to guide and teach, not write functions to fit specifications.

I do not disagree that both ozo and jkr provided code that could generate the specific random numbers.  However, neither provided explanations explaining how their code works, and neither addressed the author's additional request regarding cstrings.

As someone with administrative powers, you also have a great responsibility, to both the authors and the experts.  Truly, it was the author's responsibility to choose whichever answer best fit their needs, and if brightwood had chosen ozo's or jkr's answers, I would have said nothing.  But, brightwood has not returned, and if it is up to you to cleanup this question, I would ask that you choose the most complete answer, not simply the first.  Indeed, the author's single comment would seem to indicate that ozo's answer, at least, was not satisfactory.
0
List244Commented:
I disagree with pcgabe about the idea of giving him points based on explanation.  I think the only one that can
determine if that was helpful is the asker.  However, the asker did ask also, how to get that value into a CString.
pcgabe is the only one who helped with that and for that, I believe he should be cut in on the split.  I think that
since he is the only one whom responded to that part of the question at all, if the asker had not left, the asker
would have rewarded him points in the split.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.