• 07-17-2005
Sentral
I am making a text-football game, and decided to use rand to handle most of the tasks. Such as field goals, rushing yards, etc. Like a 50%chance of making a field goal from 40 yards. But can you only use rand once? I didn't want to try it because it would be a waste of time then. :p Here is what I am using for the coin toss:
Code:

```srand(time(0));     (rand()%2)+1;```
• 07-17-2005
sean
You seed it with srand once (so you need to make sure you don't have that call in any loops, or repetitively called functions). I like to have it as early as possible in the main() function. Then you can call rand() whenever you need another random number.
• 07-18-2005
Salem
http://faq.cprogramming.com/cgi-bin/...&id=1043284385
It seems people read the FAQ at about rand()%100 == 0 intervals.
• 07-18-2005
prog-bman
There's a FAQ?
• 07-18-2005
Sentral
Yes, there is a FAQ. I read it but didn't help too much. The part where you scale the numbers using rand, didnt even work. And my book doesn't say much about either.
• 07-18-2005
Zach L.
>> But can you only use rand once?
Use rand as often as you want. Only use srand once (before any calls to rand), but rand itself should be called for each random number you need.

>> I didn't want to try it because it would be a waste of time then.
When in doubt, trying things is often a very good idea.
• 07-18-2005
quzah
Quote:

Originally Posted by Sentral
The part where you scale the numbers using rand, didnt even work.

Somehow I doubt it. Also, there are actually two FAQs on it, not one.

Quzah.
• 07-18-2005
major_small
I'd have to agree... I tried the code from this entry:
Code:

```#include <iostream> #include <ctime> int main(void) {         int i;         srand(time(NULL));         i = rand();         std::cout <<"Your random number is " <<i <<std::endl;         std::cout <<"This compiler can generate random numbers from 0 to "                   <<RAND_MAX <<std::endl;         return(0); }```
and got this:
Quote:

jshao@MCP ~/Programming/C++ \$ g++ test.cpp -Wall -W -ansi -o test.exe
jshao@MCP ~/Programming/C++ \$ ./test.exe
This compiler can generate random numbers from 0 to 2147483647
and if you follow the link on the bottom, it shows you (correctly) how to select a range of numbers.
• 07-19-2005
Salem
> The part where you scale the numbers using rand, didnt even work.
At which point the correct response would be.

Hey I tried this from the FAQ and got these results (or non-results, or compiler errors, or ...)
• 07-19-2005
DougDbug
The Modulus Operator %
Quote:

...didnt even work.
Here's how it works - The modulus operator (the percent-sign) gives you the remainder after division. So for example, if you divide a number by 5, the remainder must be less than 5.

If you divide by 2, the remainder will be zero or one... a 50/50 chance... kinda like a coin-flip!
• 07-20-2005
Salem
I wonder if the OP did rand()%2 and was saying didn't work on the basis that they got 0101010101010101.... as the sequence?