• (2 Pages)
• 1
• 2

## Producing Random Numbers Rate Topic: 5 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=14057&amp;s=6a954f2db9a40b11ce2fcd8031ae2783&md5check=' + ipb.vars['secure_hash'], cur_rating: 2, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #16 sam lolo

Reputation: 0
• Posts: 14
• Joined: 24-September 10

Posted 27 September 2010 - 03:30 AM

### #17 ThriceSenses

Reputation: 0
• Posts: 19
• Joined: 22-March 10

Posted 04 October 2010 - 10:38 AM

Thanks, this cleared up the basics of random numbers for me.

### #18 karagulamos

Reputation: 20
• Posts: 17
• Joined: 24-November 10

Posted 13 December 2010 - 08:32 AM

There is an aspect of working with rand() function that newbies often have no idea about and are usually dumbfounded by the results. It is the proper use of the modulus operator. This is due to one or all of the following reasons.

1. Books / Authors tend to ignore this aspect when explaining the concepts to newbies.

2. Beginners are usually in a hurry to start programming instead of taking the time to understand and correctly apply concepts.

For example, what happens if we use the following code?

```int foo = 0 % 2
```

or

What is the function of the following code?

```for(int i = 0; i <= 20; i++){
std::cout << " " << i % 10;
}

```

If you've been able to answer the questions above, then you know all about the modulus operator and can now comfortably work with the rand() function Good luck with that

### #19 Guest_enginesummer*

Reputation:

Posted 17 February 2011 - 03:10 PM

i think i understand what rand and the modulus do, but i entered the code from p. 1 and every "random" number it gives me is incremented by 7! that is with or without the modulus operator which below i have //'ed out. i am running Xcode on mac osx....

```#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main ()

{
char ch;

do
{

cout << "Hit enter to generate a random number 1-99" << endl;
cin.get(ch);
srand(time(NULL));
cout << rand()// % 100 <<endl;
}
while ((ch!='q') && (ch != 'Q'));

return 0;
}

```

• Saucy!

Reputation: 6236
• Posts: 24,001
• Joined: 23-August 08

Posted 17 February 2011 - 03:28 PM

srand() should be called ONCE, and ONLY ONCE!