在下面的代码中,是否有更好的方法来排除随机数中的一个值?
enum Direction {HAUT, BAS, GAUCHE, DROITE} direction;
switch(direction)
{
case HAUT:
if (false)
{
do{direction=(rand() % 4); }while(direction!=0);
break;
}
case BAS:
if (false)
{
do{direction=(rand() % 4); }while(direction!=1);
break;
}
case GAUCHE:
..........
最佳答案
看起来你的代码总是排除当前方向(向上排除 0,向下排除 1,等等),所以你可以使用 Enum.ordinal
来决定排除而不是使用开关,像这样:
Direction direction = GAUCHE; // ...for example...
int nextDir;
do {
nextDir = rand() % 4;
} while (nextDir == direction);
direction = nextDir;
关于c - 生成一个介于 0 和 4 之间且不包括一个数字的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525886/