gpt4 book ai didi

c++ - 根据一些规则随机选择枚举值

转载 作者:行者123 更新时间:2023-11-28 03:28:00 25 4
gpt4 key购买 nike

请看下面的代码

#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. 从步行开始,他可以站立或运行
  3. 从运行开始,他可以走路
  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);

}

}
}

还是一样。现在我得到了不同的答案,但不是正确的答案!!

最佳答案

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

关于c++ - 根据一些规则随机选择枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13428135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com