請看看下面的代碼再次與隨機問題
#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);
}
}
}
}
我使用隨機的,並基於這些給定條件期望隨機結果。但是我得到的結果如下。
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
這是爲什麼?我已經嘗試過do..while循環。一點都不好。沒有什麼是檢查我在病例陳述中給出的條件。請幫忙。
請學習如何使用調試器。 –