如何分配枚举值给用户定义的双变量??c++
How to assign an enum value to a double variable defined by the user ?? C++
你好,我是一名学生,所以我想说对不起,如果我写得很累,请随时纠正我。
我有以下问题,我试图将enum int值分配给另一个双变量以进行一次乘法。因此变量costOfRoom应该取属于枚举的值D或T或S。(D = 200, T = 150 = 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;
}
用户只能输入字符。Cin将数字组转换为整型(例如123)或双精度(例如123.5)。它还将处理std::字符串(例如hello)或单个字符(例如c)的非数字分组。
一旦有了用户的输入,就可以将它们转换为枚举。您可以使用if语句,case语句或其他类型的表查找来完成此操作。
相关文章:
- 在头文件中定义变量不会出错
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 在命名空间中定义变量
- 是否可以在C++中基于程序集输出(.dll或.exe)定义变量
- 用不同类型重新定义变量
- 具有全局定义变量的递归比没有全局定义变量的递归函数获得更多的堆栈.为什么?(跳入C++)
- 定义变量类型
- 在命名空间中定义变量,但在测试中获取空值
- cmake没有定义变量
- C 中的继承:在亲子类中定义变量
- 在同一函数中定义变量及其静态等效项
- 如何在 Tensorflow C++ 中定义变量的自定义有状态 Op 保存值
- 如何将 int 和 int* 传递到函数中以定义变量
- 在定义变量时调用类函数
- 定义变量与模板
- 定义变量类型
- 为什么您可以在 switch 语句中的"默认"下定义变量,而不能在"case"下定义变量
- C 如何基于另一个变量和某些算术定义变量的值
- C 可以指向具有定义变量的函数
- C 定义变量设置值