# random number within user entered range

• 03-10-2010
me77
random number within user entered range
Code so far:

Code:

```#include <iostream> #include <cstdlib> using namespace std; int main(void){ int a, b, c,d,n, guess; cout << "enter a range of number to guess from.\n"; cin >> a >> b; d = rand() ; // need to make this within range entered by user cout << d; cout << "how many guesses do you want?\n"; cin >> c;         for (int i=0; i<c; i++){                 cout << "Enter a guess:\n";                 cin >> guess;                 if(guess == d){                         cout << "You got it!\n";                         return 0;                 }                 else if(guess < d)                         cout << "too low\n";                 else                         cout << "too high\n";         } }```
I need the random number to be within the range the user enters. I don't get how. I read about rand() %10 is 0-9.. but how do i use the users input to create a random number within their range.

thanks.
• 03-10-2010
MK27
I guess you could use rand()%(b-a) + a.
• 03-10-2010
GReaper
The general use is:
Code:

` rand() % (HIGH-LOW+1)+LOW`
Here it'll be:
Code:

` rand() % (b-a+1)+a`
• 03-10-2010
nick753
Are you even getting random numbers without seeding it?

• 03-10-2010
phantomotap
This is likely to produce a "more random" value. (It depends on the implementation of the `rand' function.)

Soma

Code:

```int random(int min, int max) {         using namespace std;         return(min + ((rand() * (1.0 / (RAND_MAX))) * (max - min))); }```
• 03-10-2010
Aisthesis
as nick mentioned, you really should seed it. here, if you're lucky, the user's entries may not make it immediately apparent, but rand() without seeding cranks out the same sequence of "random" numbers every time.

with seeding, i think sipher's formula is "random enough" for most purposes.