Thread: Need a random question answered (I mean for making random numbers ;)

1. Need a random question answered (I mean for making random numbers ;)

Okay, my first question is how do you get a random number that will either be a 1 or a 0. I can't figure out how to do that using srand() and rand(). I can get all 0's or all 1's but not random between the two.

2. Like a lot of things, this is covered very well in the FAQ. Look at the third example, it generates numbers between whatever you ask (in this case 10 and 12), what about if you told it to get numbers between 0 and 1? Take a look at how it works.

http://faq.cprogramming.com/cgi-bin/...&id=1043284385

3. Code:
```#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand((unsigned)time(0));
int what_to_do = rand()%3; // generates a random number between 1 - 3
if(what_to_do == 1)
{
// do something
}
else if(what_to_do == 2)
{
// do something
}
return 0;
}```

4. C board = C code.
C++ board = C++ code.

See the connection?

Now to your incorrect code:
Code:
`int what_to_do = rand()%3; // generates a random number between 1 - 3`
No it doesn't. It makes a random number between 0 and 2. And why do you have three choices, when you only use two of them? There's a 33% chance your program will do nothing when it runs.

Quzah.

5. Thanks for the help guys. Can't believe I never figured that simple thing out.

Popular pages Recent additions