【问题标题】:How to use the enum when selecting type of operations选择操作类型时如何使用枚举
【发布时间】:2020-12-14 16:29:49
【问题描述】:

我正在尝试创建一个具有算术运算的数学游戏,例如加法 (+)、减法 (-)、乘法 (*) 和除法 (/),用户可以在其中选择哪一个运算他们想要选择的四个。我想知道到目前为止我只包括了四种不同类型的操作如何使用枚举

enum class Operations{
    Add,
    Subtract,
    Multiply,
    Divide,
};

我现在不知道在那之后要添加什么。

【问题讨论】:

  • 创建一个操作变量(枚举对象)并让用户选择其中一个操作。您必须提供更多信息以供任何人帮助

标签: c++ c++11 visual-c++


【解决方案1】:

虽然枚举可能会产生问题,但在您的情况下,使用普通枚举是可行的。枚举成员隐式转换为 int。这可以帮助您确定用户想要执行的操作。

enum Operation
{
  Add, //0
  Subtract, //1
  Multiply, //2
  Divide //3
}operations_e;

接下来,从用​​户那里获取操作数

cin>>a;
cin>>b;

接下来,获取用户想要执行的操作:

cout<<"Enter the operation you want to perform"<<endl;
cout<<"Enter 0 for ADD"<<endl;
cout<<"Enter 1 for SUBTRACT"<<endl;
cout<<"Enter 2 for MULTIPLY"<<endl;
cout<<"Enter 3 for DIVIDE"<<endl;

//Take user input into enum variable
cin>>operations_e;

接下来,切换枚举

switch(operations_e)
{
  case Add:
   //add the operands
   break;
  case Subtract:
   //subtract operands
   break;
  case Multiply:
   //multiply operands
  break;
  case Divide:
   //divide operands
   break;
  default:
   //add default case. Not necessary for enums as they are robust
   //but a good practice mention the default case
  break;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2022-01-15
    • 2022-08-22
    • 1970-01-01
    相关资源
    最近更新 更多