i have to do with my new assignment
but the problem is not im don't try to do it at all
i've tried it before..the question is to write a c++ program about ask the user an input of a range of numbers.by using the rand() an output of three random numbers will be selected...ive tried this ;

                        int generate_numbers (int min,int max)
                        {   for (int i=1;i<=3;i++)
                            {int ans=rand ()%max+min;

then after that i call the function in main function but the output is not display as what im expecting..let say i enter range 10-20,the output will be 11 17 24..
how could be 24?and from this three random numbers,,how i may get the largest and smallest number between the three random numbers???help me pleeeaaasss~~~i need to submit this by nex week..pleeeaaaassss~~~

Edited by Dani: Formatting fixed

6 Years
Discussion Span
Last Post by Unimportant

Think about what you're doing.
You know that if you want a max random value of 20, you do:

So this will generate something between 0 and 20.
Now the problem starts when you try to deal with the min value, you simply add min(10) to the randomly generated number between 0 and 20.

So, what happens if rand()%20 returns 14?
14 is between 0 and 20 so that is absolutely possible.


yahhh..u'r rite
but the thing is let say my range is not start from 0..
ok..let say i declare my parameter as (int min,int max)
then i make a formula for the random numbers..
int ans=rand()%max+min...rite??let say in main function,,i enter number 10 for min,20 for max.
what happen in the formula is rand()%20+10..what's that mean?
because the output is exceeded this range...


instead of using parameters like this:
int foo( int min, int max );

why not:

int range_rand( int a, int b ) {
  int high, low;
  int ans=rand()%high; // I'm assuming you seeded rand already
  if( ans < low ) ans+=low; // this won't actually work if your range is too small, so you'll need to give some thought to this line
  // such as adding the difference between high and low (as rand()%(high-low)), instead of low, and adding it to ans until ans is >= low
  return ans;

Edited by Unimportant: n/a


Oh just a side note, but I wouldn't use your approach at all:

return low+int((high-low+1)*rand()/(RAND_MAX+1.0));

but that's just me

What I mean is, why aren't you just offsetting your range once you already have an element of the subset selected?

Edited by Unimportant: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.