如何在rand()函数中使用枚举值

时间:2017-11-18 22:55:49

标签: c++ random enums

如何使用生成随机枚举变量的rand函数?这是我到目前为止(它正在吐出垃圾数字):

enum pieces { FLAG = 'F', BOMB = 'B', MARSHAL = '1', GENERAL = '2', COLONEL = 
              '3', MAJOR = '4', CAPTAIN = '5', LIEUTENANT = '6', SERGEANT = 
              '7', MINER = '8', SPY = 'S' };

int gamePieces[12] = { FLAG, BOMB, MARSHAL, GENERAL, COLONEL, MAJOR, 
                       CAPTAIN, LIEUTENANT, SEGEANT, MINOR, SPY };

int rand_piece = (rand()& gamePieces[12];

3 个答案:

答案 0 :(得分:1)

可能严格来说是不可能的。 你可以

  1. 检查这些枚举中的值是什么值
  2. 然后你就可以生成一个整数
  3. 对其进行模数(%)
  4. 解析为枚举[编辑 - 您不必将其解析为C ++中的枚举]
  5. 例如

    #include <iostream>
    #include <stdlib.h>  
    using namespace std;
    
    int main()
    {
       enum gamePieces { FLAG, BOMB, MARSHAL, GENERAL, COLONEL, MAJOR, 
                           CAPTAIN, LIEUTENANT, SEGEANT, MINOR, SPY };
    
       int maxEnumValue = 12;
       int randPiece = rand() % maxEnumValue;
       cout << randPiece;
    }
    

答案 1 :(得分:0)

您可以使用rand() % 12,这将创建一个0-11范围内的随机数:

int rand_piece = gamePieces[rand() % 12];

您的代码中存在更多错误 - 请尝试以下操作:

#include <stdlib.h>

const int numPieces = 11;

enum pieces { FLAG = 'F', BOMB = 'B', MARSHAL = '1', GENERAL = '2', COLONEL = 
              '3', MAJOR = '4', CAPTAIN = '5', LIEUTENANT = '6', SERGEANT = 
              '7', MINER = '8', SPY = 'S' };

int gamePieces[numPieces] = { FLAG, BOMB, MARSHAL, GENERAL, COLONEL, MAJOR, 
                       CAPTAIN, LIEUTENANT, SERGEANT, MINER, SPY };

int rand_piece = gamePieces[rand() % numPieces];

或者,如果您不需要额外的价值:

enum pieces { FLAG, BOMB, MARSHAL, GENERAL, COLONEL, MAJOR, 
              CAPTAIN, LIEUTENANT, SERGEANT, MINER, SPY,
              MAX_PIECE };

int rand_piece = rand() % MAX_PIECE;

答案 2 :(得分:0)

尝试:

int main()
{
    enum pieces {
        FLAG = 'F', BOMB = 'B', MARSHAL = '1', GENERAL = '2', COLONEL =
        '3', MAJOR = '4', CAPTAIN = '5', LIEUTENANT = '6', SERGEANT =
        '7', MINER = '8', SPY = 'S'
    };

    int gamePieces[11] = { FLAG, BOMB, MARSHAL, GENERAL, COLONEL, MAJOR,
        CAPTAIN, LIEUTENANT, SERGEANT, MAJOR, SPY };


    std::cout << char(gamePieces[rand() % 11]) << std::endl;
    std::cout << char(gamePieces[rand() % 11]) << std::endl;
    std::cout << char(gamePieces[rand() % 11]) << std::endl;
    std::cout << char(gamePieces[rand() % 11]) << std::endl;
    std::cout << char(gamePieces[rand() % 11]) << std::endl;

    return 0;
}

打印:

7
4
4
B
6