I have the following code in a program that compiles ok, and runs without crashing, but it only ever executes the first 2 switch cases. In fact, It almost always executes case 0, and rarely case 1.
How can I get the program to occasionally run one of the other 2 cases?
... //other code
#include %26lt;ctime%26gt;
#include %26lt;cstdlib%26gt;
... //other code
int randNum;
srand(time(0));
do
{
randNum = rand() % 4;
switch(randNum)
{
case 0:
//code
break;
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
default:
//code
break;
}
}
while(condition);
P.S. forgive the bad formatting, I can't seem to make things indent properly.
C++ rand() function trouble?
It looks right from what you have there. Here's a video explanation of how the function works:
http://xoax.net/comp/cpp/console/Lesson2...
You might try a simpler example to and make some variations to make sure that your compiler implementation is correct. However, the rand() should generate a uniform distribution.
Reply:Where is it called "randomize()"? It's called srand() in Linux usually.
BTW, using the modulus may not be the best adivce. If this is Linux, I'd try something like:
randNum = rand()*4/(RAND_MAX + 1);
Reply:Call randomize() after the line 'randNum = rand() % 4;'
It will help to generate different different numbers in the particular range
magnolia
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment