# Thread: random number within user entered range

1. ## 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.

2. I guess you could use rand()%(b-a) + a.

3. The general use is:
Code:
` rand() % (HIGH-LOW+1)+LOW`
Here it'll be:
Code:
` rand() % (b-a+1)+a`

4. Are you even getting random numbers without seeding it?

to seed the radndom numbers you declare srand(time(NULL)); below your int's.

also you'll have to include <ctime> in your header files.

5. 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)));
}```

6. 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.

Popular pages Recent additions