c++ - 如何将枚举值分配给用户定义的 double 变量?? C++

标签 c++ enums

您好,我是一名学生,所以我想说声抱歉,如果我写得很累,请随时指正。

我遇到以下问题 我正在尝试将一个枚举 int 值分配给另一个 double 变量以进行一次乘法运算。 所以变量 costOfRoom 应该取属于枚举的值 D 或 T 或 S。 (D=200,T=150,S=110)

这必须由用户完成。

但找不到任何方法,我试图将第二个变量设为字符串类型,但它再次不起作用。它只会像字符串一样正常使用字符:(

还尝试了 cin >> type_Ofroom costofroom ; 但我认为这是在 Java 中使用的??

搜了论坛也没有类似的答案:(

程序运行良好,没有任何编译错误:)

谢谢你的时间

/* build a software system which will allow a hotel receptionist,
to enter in bookings for guests who come to the desk.
The system should display the room options as:
Room        Price       Code
---------------------------------------------------------------
Deluxe Room £200         D
Twin Room       £150     T
Single      £110         S

The receptionist should be prompted to enter in the room type and the number of 
nights a guest wishes to stay for and then calculate the amount
they need to pay. 
   */

// solution 
#include <iostream>
using namespace std;
int main() {

    // decleration of variables 
    double number_OfDays = 0, Totalcost = 0, costofroom = 0;
    enum   type_Ofroom { D = 200, T = 150, S = 150 };
    cout << "enter the type of the room " << endl << endl;

    //input of room type
    cin >> costofroom; // **here is the problem**  i am trying to give the 
                       //    values of the enum varaiable 
                        // it should have D or T or S but i cant  make it
    cout << "enter the number of the days " << endl << endl;

    //input of days
    cin >> number_OfDays;

    // calculation 
    Totalcost = costofroom * number_OfDays;

    // result 
    cout << "the costumer has to pay " << Totalcost << " pounds" << endl << endl;
    return 0;
}

最佳答案

您可以读入一个double,然后检查您的enum 值:

//input of room type
while (1)
{
    cin >> costofroom;
    if (costofroom == 0.0)
        costofroom = D;
    else if (costofroom == 1.0)
        costofroom = T;
    else if (costofroom == 2.0)
        costofroom = S;
    else
    {
        cout << "You didn't enter a valid option" << endl;
        continue;
    }
    break;
}

但是,最好读入一个int,然后再设置您的double

double costofroom;
int option;

...

//input of room type
while (1)
{
    cin >> option;
    if (option == 0)
        costofroom = D;
    else if (option == 1)
        costofroom = T;
    else if (option == 2)
        costofroom = S;
    else
    {
        cout << "You didn't enter a valid option" << endl;
        continue;
    }
    break;
}

关于c++ - 如何将枚举值分配给用户定义的 double 变量?? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33004115/

相关文章:

c++ - CORDIC 用于平方根

c++ - 在C++中对数组使用阶乘函数

c++ - C++ 宏可以在 C++ 文件末尾添加一些代码吗?

java:将枚举注入(inject)应用程序范围

sql - 我应该为主键和外键使用 ENUM 吗?

c++ - 尽管找到了 cuda,CMAKE_CUDA_COMPILER 标志仍为 false

c++ - 带有-stdlib = libc++的clang++ 9.0.1无法找到<optional>

java - 使用 values( ) 创建枚举常量的最终 Java 类数组

java - 当我将 Enum 实例变量设置为作为选项包含在 Enum 类本身中的值时,它无法解析为类型。为什么?

swift - 基于字符串的枚举是否有 Swift 类型?