Geeks To Go is a helpful hub, where thousands of volunteer geeks quickly serve friendly answers and support. Check out the forums and get free advice from the experts. Register now to gain access to all of our features, it's FREE and only takes one minute. Once registered and logged in, you will be able to create topics, post replies to existing threads, give reputation to your fellow members, get your own private messenger, post status updates, manage your profile and so much more.

Create Account How it Works

# Limiting a random number? (C++)

### #1 Throntel Posted 03 February 2006 - 04:14 PM

Throntel

Member

• Member
• 39 posts
when I make a random function in a variable like this:

int a = rand();

How do I then limit the rand(); To only randomize betweem numbers from 0-10?
I thought it might be:

int a = rand(0-10);

But it didn't work so I guess that was wrong, also I were wondering how I can make the random funktion include comma (like: 2,34)...

Please respond to this Probably easy for you real geeks out there, I'm currently just a wannabe
• 0

### #2 destin Posted 03 February 2006 - 09:58 PM

destin

Member

• Member
• 53 posts
It is really quite simple. What you are trying to do is put an integer argument (0-10 = -10) into the rand() method. It is not overloaded to do that. You obviously were trying 0 through 10, but the '-' operator subtracts.

An easy way to get a random number from 0 to 10 is to simply use the modulus operator:
```int rnd = rand() % 10;
```
Any number % 10 will give you either 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. If you want to set a range, you can use basic math:
```int rand(int min, int max) {
return rand() % (max - min + 1) + min;
}```
Say you want a random number from 5 to 7, you would call it like this: rand(5, 7);
This will mod a random number by 3 (7 - 5 + 1). Now you have a number that is either 0, 1, or 2. Add 5, and you have a number 5, 6, or 7.

As for displaying random number with a comma, you can just append a comma to then end of a random number. For instance, if I wanted to display 5 random numbers:
```for (int i = 0; i < 5; i++) {
cout << rand(0, 10);
if (5 - i > 1) { // we don't want to add an extra comma at the end
cout << ", ";
}
}
```
Hope this helps!

Edited by destin, 04 February 2006 - 11:57 AM.

• 0

### #3 Throntel Posted 04 February 2006 - 05:36 AM

Throntel

Member

• Topic Starter
• Member
• 39 posts
Yeah, it really did.
Thanks for you're help
• 0

### Similar Topics

#### 0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users