如何在c++中为程序添加while循环

How to add a while loop to this program in C++

本文关键字:程序 添加 while 循环 c++      更新时间:2023-10-16

我的程序运行了,格式正确,但我应该把整个东西放在一个循环中,允许程序运行,直到用户输入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;
}

我会尝试一些类似的代码:

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
    }
}