0

请看下面的代码

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    enum Movement{STAND,WALK,RUN,CRAWL};

    Movement state = (Movement)(1+rand()%4);

    for(int i=0;i<100;i++)
    {

    cout << state << endl;

    switch(state)
    {
        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);}

    }

    }
}

在这里,规则很少。让我们称它们为合法过渡

  1. 从站立,他可以走路或爬行
  2. 从 Walk 开始,他可以站立或奔跑
  3. 从Run,他可以走路
  4. 从爬行,他可以站立

因此,在这里,是否应该随机选择合法转换。但是,它应该根据上面提供的规则。例如,如果选择了“STAND”,那么接下来要选择的应该是“WALK”或“CRAWL”。但正如你在这里看到的,所有的结果

2
You can walk

这是为什么?请帮忙!

更新:

以下代码使用 do..while 循环,正如回复中所建议的那样

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    enum Movement{STAND,WALK,RUN,CRAWL};

    Movement state = (Movement)(1+rand()%4);

    for(int i=0;i<10;i++)
    {

    cout << state;

    if(state==STAND)
    {
        cout << " STAND is selected" << endl;

    }
    else if(state==WALK)
    {
        cout << " WALK is selected" << endl;

    }
    else if(state==RUN)
    {
        cout << " RUN is selected" << endl;
    }
    else if(state==CRAWL)
    {
        cout << " CRAWL is selected" << endl;
    }

    switch(state)
    {
        case STAND: 
            //cout << "You can walk or crawl" << endl;        
            do{state = (Movement)(rand()%4);}
            while(state==WALK || state==CRAWL);

            break;


        case WALK: 
            //cout << "You can stand or run" << endl;
            do{state = (Movement)(rand()%4);}
            while(state==STAND || state==RUN);
            break;


        case RUN: 
            //cout << "You can walk" << endl;
            do{state = (Movement)(rand()%4);}
            while(state==WALK);
            break;

        default: 
            //cout << "You can stand" << endl;
            do{state = (Movement)(rand()%4);}
            while(state==STAND);

    }

    }
}

它仍然是一样的。现在我得到不同的答案,但不是正确的!

4

2 回答 2

1

在 C 和 C++ 中,枚举默认从 0 开始。

于 2012-11-17T06:01:30.520 回答
1

您的逻辑顺序错误;你的while循环都将被跳过,因为state它仍然是你输入特定的case. 您可以重写它们do-while以确保它们至少运行一次。

于 2012-11-17T06:02:28.503 回答