2015-04-04 71 views
-1

你好,我开始学习C++,我不知道如何枚举工作那么好,我需要帮助,我知道如何让兰特()与枚举如何在枚举中使用rand()?

#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()选择随机性质,请任何帮助):?

+0

在这种情况下,C++中的枚举只是一系列int(0-3)的简便表示。 – 2015-04-04 04:53:09

+0

如何在默认情况下使用rand():? – Cereal 2015-04-04 04:56:24

回答

0

由于从http://www.cprogramming.com/tutorial/enum.html采取:

印刷枚举

你可能不知道发生了什么,当你打印出一个枚举:默认情况下,你会得到枚举的整数值。如果你想做一些比这更奇妙的事情,你必须专门处理它。

您将不得不创建另一个开关块,将随机整数转换为enum中的适当值。另外,还可以通过srand(time(NULL))

为您的随机数生成器初始化一个种子,并将rand值也分配给WeaponNature。

+0

噢,谢谢,你和Phillip对我有些触动,现在我得到一个枚举,ty/case解决了:D – Cereal 2015-04-04 05:04:08