如何在c++中为程序添加while循环
How to add a while loop to this program in C++
我的程序运行了,格式正确,但我应该把整个东西放在一个循环中,允许程序运行,直到用户输入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
}
}
相关文章:
- 在没有管理员权限的情况下,在 c++ 中以编程方式将程序添加到启动
- 如何将我的程序添加到文件和文件夹的macOS右键单击菜单?
- 如何将信号处理程序添加为方法
- 如何向控制台应用程序添加图标
- 不知道如何向我的程序添加循环...?
- 将事件处理程序添加到C 中的按钮
- C 从内部程序代码上将应用程序添加到Linux程序上的启动中
- 将事件处理程序添加到任何控件都会导致 Visual Studio 中出错
- 如何自动将处理程序添加到全局映射
- C++程序添加逗号以延长数字
- 如何将事件处理程序添加到桌面窗口
- 向MFC应用程序添加许可保护
- 向iOS应用程序添加64位切片会导致崩溃
- 运行时向程序添加算法
- 向程序添加详细程度
- 向Win32应用程序c++添加基本文本
- 程序添加一个用户到MySQL
- 为c++控制台应用程序添加状态栏
- 向程序添加排序算法(冒泡排序)
- 向现有的MFC应用程序添加控制台