0

我的程序运行并且格式正确,但我应该将整个事情放在一个循环中,允许程序运行直到用户输入 6 退出。每次用户购买时,应该从机器中的饮料中减去 1。售罄时会显示“已售罄”。所以循环应该重复并显示机器赚取的总金额。我不知道如何将整个程序放入一个while循环(我猜)这样请帮助

#include <iomanip>
#include <iostream>
#include <string>
using namespace std;


struct Drink
{
    string drinkName;
    double cost;
    int numberInMachine;
};

struct Drink options[] = {{"Cola", .75, 0}, {"Root Beer", .75, 2},
                      {"Lemon-Lime", .75, 10},
                      {"Grape Soda", .80, 3}, {"Cream Soda", .80, 20}};

int getChoice();
double showTransaction(int);

int main()
{
    int choice;
    double moneyEarned = 0.0;

    choice = getChoice();
    moneyEarned = showTransaction(choice);

    cout <<"The machine earned: $" << moneyEarned << endl;


    //getChoice();
    //showTransaction(options, NUM_DRINKS, choice);


    system("pause");
    return 0;
}

int getChoice()
{
    int choice;

    cout << "Enter the number(1-6) of the drink you would like: " << endl;
    cout << "Drink Name         Cost            " << endl; 
    cout << "1. Cola            .75             " << endl;
    cout << "2. Root Beer       .75             " << endl;
    cout << "3. Lemon-lime      .75             " << endl;
    cout << "4. Grape Soda      .80             " << endl;
    cout << "5. Cream Soda      .80             " << endl;
    cout << "6. Quit " << endl;

    cout << " Enter the number of your selection: ";
    cin >> choice;

    while(choice != 1 && choice != 2 && choice !=3 && choice != 4 
                      && choice != 5 && choice != 6)
    {
            cout << "Please enter a valid number 1-6" << endl;
            cin >> choice;
    }

    return choice;
}
double showTransaction(int choice) 
{
    double moneyIn;

    if(options[choice - 1].numberInMachine < 1)
    {
        return 0.0;
    }

    cout << options[choice - 1].drinkName << "costs $" 
         << options[choice - 1].cost << endl;
    cout << "Enter money inserted up to $1.00: ";
    cin >> moneyIn;
    while(moneyIn < options[choice - 1].cost)
    {
        cout << "The money entered is not enough, please enter more: ";
        cin >> moneyIn;
    }
    cout << "Your change is: $" << (moneyIn - options[choice - 1].cost) 
                 << endl;

    return moneyIn;

}
4

1 回答 1

1

我会尝试一些东西(一些粗略的代码):

for( ; ; ) {                      // infinite loop
    choice = getChoice();         // original code
    if( choice == 6 ) {
        break;                    // break out of loop and exit
    }
    moneyEarned = showTransaction(choice);        // original code
    if( moneyEarned < 0.01 ) {
        break;                    // break out of loop and exit
    }
}
于 2013-05-01T00:17:31.000 回答