Please have a look at the following code
#include <iostream>
#include <stdlib.h>
#include <ctime>
using namespace std;
int main()
{
enum Movement{STAND=1,WALK,RUN,CRAWL};
srand(time(0));
Movement state = (Movement)(1+rand()%4);
for(int i=0;i<10;i++)
{
cout << state << endl;
switch(state)
{
/*Here the logic is,
*
* 1. From stand, he can walk or crawl
2. From Walk, he can stand or run
3. From Run, he can walk
4. From Crawl, he can stand
*/
case STAND:
cout << "You can walk or crawl" << endl;
while(state==WALK || state==CRAWL)
{
state = (Movement)(1+rand()%4);
}
break;
case WALK:
cout << "You can stand or run" << endl;
while(state==STAND || state==RUN)
{
state = (Movement)(1+rand()%4);
}
break;
case RUN:
cout << "You can walk" << endl;
while(state==WALK)
{
state = (Movement)(1+rand()%4);
}
break;
default:
cout << "You can stand" << endl;
while(state==STAND)
{
state = (Movement)(1+rand()%4);
}
}
}
}
I am using random, and expecting random results based on those given conditions. But I am getting the same result as below.
2
You can stand or run
2
You can stand or run
2
You can stand or run
2
You can stand or run
2
You can stand or run
2
You can stand or run
2
You can stand or run
2
You can stand or run
2
You can stand or run
2
You can stand or run
why is this? I have tried do..while loops as well. No good at all. Nothing is checking the conditions I have given in case statements. please help.
Flip your while-loops to do-while. The expressions are invalid as well for the checks (unless it was your intention they NOT match the text). The states, according to the messages are:
So the sections need to be changed to
The latter part is important for the Run and Crawl states. Since they can only produce ONE valid result state, spinning a rand() call looking for that value makes no sense. Just set the new state and loop again.
Regarding (2) above:
Becomes…
Regarding the Run and Crawl states:
That leaves you one more to check yourself, which I leave to you.