# Use of rand() function

Page 1 of 1

## 4 Replies - 40650 Views - Last Post: 10 October 2005 - 10:19 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=12660&amp;s=37a513aac432fb6e49d53920417ee7df&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 ExitToShell();

Reputation: 0
• Posts: 26
• Joined: 09-October 05

# Use of rand() function

Posted 10 October 2005 - 09:28 AM

This is my first post in the C++ section, so I'll just say it now that I'm teaching myself with two textbooks(one for the lessons, the other for "labs" of a sort to make sure you know your stuff), but I'm not being graded

Alright, as I learn I've been adding on little tidbits of code here and there to a little rpg I doubt will ever finish

The question I have involves that:

For the random function ( rand() ), how could I get it to give me a random number 2-4, if rand() only gives a random number between 0 and whatever number you give it?

Is This A Good Question/Topic? 0

## Replies To: Use of rand() function

### #2 dorknexus

Reputation: 1272
• Posts: 4,625
• Joined: 02-May 04

## Re: Use of rand() function

Posted 10 October 2005 - 09:31 AM

just get a random number between 0 and 2 and add 2 to it. the best rule to remember is to set up the function like this

```int num = rand() % (HIGH - LOW) + LOW;

```

in this case high = 4 and low = 2

```int num = rand() % (4 -2) + 2;

//or

int num = rand() % (2) + 2;

```

### #3 ExitToShell();

Reputation: 0
• Posts: 26
• Joined: 09-October 05

## Re: Use of rand() function

Posted 10 October 2005 - 09:44 AM

Wow, that was a quick reply, you guys are fast

Thank you, this has helped me finish implementing an equation

### #4 dorknexus

Reputation: 1272
• Posts: 4,625
• Joined: 02-May 04

## Re: Use of rand() function

Posted 10 October 2005 - 09:45 AM

Not a problem, hope DIC can be just as helpful for you in the future.

### #5 born2c0de

• printf("I'm a %XR",195936478);

Reputation: 187
• Posts: 4,673
• Joined: 26-November 04

## Re: Use of rand() function

Posted 10 October 2005 - 10:19 PM

You can use the random() function as well for simple ranges.
```#include <stdlib.h>
#include <stdio.h>
#include <time.h>

/* prints a random number in the range 0 to 99 */
int main(void)
{
randomize();
printf("Random number in the 0-99 range: %d\n", random (100));
return 0;
}

```