如何在枚举中使用rand()?

时间:2015-04-04 04:46:48

标签: c++ random enums switch-statement

您好我开始学习c ++,我不明白enum是如何工作的,我需要帮助知道如何让rand()与enum一起工作

#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>

using namespace std;

int main()
{

    cout << "First part : Create an item. " << endl;
    int choice;

    int Fire = 25;
    int Water = 23;
    int Wind = 24;
    int Earth = 20;
    
    int WeaponNature = 0;
    
    enum NatureWeapons { Fire, Water, Wind, Earth}; // enum here if its wrong pls let me know ): 
    
   
    
    cout << "Enter the nature of weapon you want : " << endl;
    cout << " 1 - Fire " << endl;
    cout << " 2 - Water " << endl;
    cout << " 3 - Wind " << endl;
    cout << " 4 - Earth" << endl;
    cin >> choice;
    switch(choice)
    {
        case 1:
        cout << "You picked fire."
        cout << " Power : " << Fire << endl;
        WeaponNature = Fire;
        break;
        
        case 2:
        cout << "You picked water." << endl;
        cout << " Power : " << Water << endl;
        WeaponNature = Water;
        break;
        
        case 3:
        cout << "You picked wind nature." << endl;
        cout << " Power : " << Wind << endl;
        WeaponNature = Wind;
        break;
        
        case 4:
        cout << "You picked earth nature." << endl;
        cout << " Power : " << Earth << endl;
        WeaponNature = Earth;
        break;
        
        default:
        cout << "Incorrect input. Your weapon will be : " << rand() // this is where i need help 
        
    }
    


}

当默认:在switch()中运行时,我希望它选择rand()的随机性,请任何帮助):?

1 个答案:

答案 0 :(得分:0)

http://www.cprogramming.com/tutorial/enum.html开始:

  

打印枚举

     

您可能想知道打印枚举时会发生什么:默认情况下,您将获得枚举的整数值。如果你想做一些比这更好的事情,你将不得不专门处理它。

您必须创建另一个开关块,将随机整数转换为枚举中的正确值。另外,通过srand( time( NULL ) )

为随机数生成器初始化种子

也将rand值分配给WeaponNature。