Public Group

#### Archived

This topic is now archived and is closed to further replies.

# Generating Random numbers

This topic is 5684 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How can I generate a random number in the range 1 to 21 in Visual C++?! I thought this would be a trival task but I can only find the Rand() function which returns a random number in the range 1 to 36000.

##### Share on other sites
int myrand( int from, int to )
{
return (rand()%(to-from)) + from;
}

myrand( 1, 21 );

There is a better way, just can''t seem to recall it..

##### Share on other sites
first so you don''t get the same value over and over put this line at the start of your program:

<code>srand(time(NULL));</code>

then to get a value between 1 and 21 use this -

<code>int randNumber = (rand()/RANDMAX)*21 + 1</code>

without the + 1 it would be 0-20

##### Share on other sites
first so you don''t get the same value over and over put this line at the start of your program:

<code>srand(time(NULL));</code>

then to get a value between 1 and 21 use this -

<code>int randNumber = (rand()/RAND_MAX)*21 + 1</code>

without the + 1 it would be 0-20

##### Share on other sites
First, it is 0 to RAND_MAX not 1 to 36000. Second, R1to21 = rand()*20/RAND_MAX+1

##### Share on other sites
#include(cstdlib); //random function replace '(' with '<'
#include(iostream);

using std::cout;
using std::endl;

int main()
{

int randomnumber; //holder for random number
int maxnumber= 1000; //the max number we want
int minnumber = 1; //the min number we want

srand(time(0)); //seeds random so we get a different number each run

randomnumber = minnumber+rand() %maxnumber; //generates number

cout << randomnumber <
return 0;
}

[edited by - Aaron71771 on March 4, 2003 5:18:29 PM]

##### Share on other sites
I am going to make this question part of the tech test. Four posts - three errors.

Thanks all.

##### Share on other sites
const SHNUM = 21;
int picknum()
{
int number;
number = (rand() % SHNUM);
return(number);
}

int main()

{

int theNumber; // the randomly generated # will be stored in this variable

srand((unsigned)time(NULL));
theNumber = picknum() + 1;

}

there ya go, stores a random number between 1 and 21 in the variable theNumber, hope that helps!

##### Share on other sites
Simply use this:

random_number = 1 + rand()% 21;

1. 1
2. 2
3. 3
4. 4
Rutin
12
5. 5

• 12
• 16
• 10
• 14
• 10
• ### Forum Statistics

• Total Topics
632659
• Total Posts
3007692
• ### Who's Online (See full list)

There are no registered users currently online

×