我有这个项目用于学校及其用于简单的自动售货机。我想知道如何根据用户的需要多次执行我的功能,并跟踪机器内部的可用更改。
#include <iostream>
#include <string>
using namespace std;
void changecalculator (int purchaseAmount, int& Qav, int& Dav, int& Nav)
{
int QBack ,DBack ,NBack ;
int chaneBack = 100 - purchaseAmount ;
if (purchaseAmount %5 == 0)
{
cout << "You entered a purchase amount of " << purchaseAmount << " cents." <<endl;
cout <<endl;
QBack = std::min(chaneBack / 25, Qav) ;
chaneBack -= QBack * 25 ;
DBack = std::min(chaneBack/10, Dav);
chaneBack -= DBack* 10;
NBack = std::min(chaneBack/ 5, Nav);
chaneBack = QBack*25 + NBack*10 + DBack*5 ;
int coinsNum = QBack + DBack + NBack;
cout <<"Your change of " <<chaneBack <<" cents is given as " <<QBack <<" Q, " <<DBack <<" D,and " <<NBack <<" N." <<endl;
cout << "The value of your " <<coinsNum <<" coins adds up to " <<chaneBack <<" cents." <<endl;
cout << "Thank you for using my program." <<endl;
Qav -= QBack;
Dav -= DBack;
Nav -= NBack;
cout << "Quarters available: " <<Qav <<endl;
cout << "Dimes available: " <<Dav <<endl;
cout << "Nickels available: " <<Nav <<endl;
}
else
{
cout << "Unable to process an invalid purchase amout of " <<purchaseAmount <<" cents." <<endl;
cout << "Thank you for using my program." <<endl;
}
}
int main()
{
//set the variables
int Qav=5 ;
int Dav=5 ;
int Nav=5 ;
int purchaseAmount ;
string answer;
cout << "Simple Vending Program for Adam Ashouri (Regular Version)" <<endl;
cout <<endl;
cout <<endl;
cout << "Enter a purchase amount [5 - 100] -->";
cin >> purchaseAmount;
changecalculator (purchaseAmount, Qav, Dav, Nav);
cout << "Process again (y/n)?";
cin >> answer;
}
答案 0 :(得分:3)
类似于do{} while()
循环?
do
{
cout << "Simple Vending Program for Adam Ashouri (Regular Version)" <<endl;
cout <<endl;
cout <<endl;
cout << "Enter a purchase amount [5 - 100] -->";
cin >> purchaseAmount;
changecalculator (purchaseAmount, Qav, Dav, Nav);
//get userResponse;
}
while(userResponse =='y' || userResponse =='Y');
答案 1 :(得分:2)
while
循环可能很好:
while(answer == "y"){
cout << "Simple Vending Program for Adam Ashouri (Regular Version)" <<endl;
cout <<endl;
cout <<endl;
cout << "Enter a purchase amount [5 - 100] -->";
cin >> purchaseAmount;
changecalculator (purchaseAmount, Qav, Dav, Nav);
cout << "Process again (y/n)?";
cin >> answer;
}