[英]How to assign an enum value to a double variable defined by the user ?? C++
您好,我是一名学生,所以我想对不起,以防我的论文累人,请随时纠正我。
我遇到以下问题,我试图将一个枚举int值分配给另一个双精度变量以进行一个乘法。 因此变量costOfRoom应该采用属于枚举的值D或T或S。 (D = 200,T = 150,S = 110)
这必须由用户完成。
但是找不到任何方法,我试图将第二个变量设置为字符串类型,但无法再次使用。 它只会像字符串一样正常使用chars :(
还尝试了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会将数字分组转换为int(例如123)或double(例如123.5)。 它还将处理非数字分组为std :: strings(例如,hello)或单个字符(例如,c)。
输入用户的输入后,可以将其转换为枚举。 您可以使用if语句,case语句或某种类型的表进行查找。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.