簡體   English   中英

如何將枚舉值分配給用戶定義的雙精度變量? C ++

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM