I’m having problems below. In my howmany function, it is supposed to read in how much money you have and the cost a item, then it’s supposed to tell you how many of that item you can buy and the money leftover. So far all I can get it to display is a 0 for number of items allowed and money is displayed as the original amount entered.
Any help would be appreciated, also whenever I hit Q to quit the program I have to enter it 2 or 3 times for the loop to actually stop.
#include <iostream>
using namespace std;
void bestbuy(double&, double&, double);
void discountresults (double&, double&);
void howmany(double&, double&);
char menu();
double price1, price2, price3;//bestbuy variables
double price, discount;//discountresults variables
double cash,item;//howmany variables
int main ()
{
char choice;
do
{menu();
choice = menu();}
while(choice != 'Q');
menu();
system ("PAUSE");
return 0;
}
void bestbuy(double &val1,double &val2, double val3)
{
if (val1 < val2 && val1 < val3)
val2 = 1;
else if (val2 < val1 && val2 < val3)
{val1 = val2;
val2 = 2;}
else
{val1 = val3;
val2 = 3;}
}
void discountresults(double &price, double &discount)
{
double hold;
hold = price;
price *= discount; //discount amount
hold -= price;
discount = hold; //price after discount
}
void howmany(double &money, double &itemcost)
{
double items;
items = money / itemcost;
itemcost = itemcost * items;
money = money - itemcost;
}
char menu()
{
char option;
cout<<"(B)est Buy Calculation.\n";
cout<<"(D)iscount Calculation.\n";
cout<<"(H)ow Many Calculation.\n";
cout<<"(Q)uit.\n";
cout<<"Please enter the option B, D, H, or Q\n";
cin>>option;
switch(option)
{
case 'B':
cout<<"Please enter 3 prices\n";
cin>>price1;
cin>>price2;
cin>>price3;
bestbuy(price1,price2,price3);
cout<<"Your lowest price entered was "<<price1<<" and it was the "<<price2<<" number you entered.\n";
break;
case 'D':
cout<<"Please enter price of item and discount percent\n";
cin>>price;
cin>>discount;
discountresults(price,discount);
cout<<"Your discount amount is "<<price<<" and the discounted price is "<<discount<<endl;
break;
case 'H':
cout<<"Please enter amount of money available and cost of item\n";
cin>>cash;
cin>>item;
howmany(cash,item);
cout<<"You can buy "<<cash<<" of that item and have $"<<item<<" left over\n";
break;
case 'Q':
return option;
}}
Mathematically, this function will always return zero:
itemcost = itemcost * (money / itemcost)always evaluates tomoney(to a numerical error). Thereforemoney - itemcostequals zero (again, to a numerical error).You need to take into account the fact that you can only buy a whole number of items. Since this is homework, figuring out the best way to do this is left as an exercise.
Also bear in mind that when you pass things by reference, the modified values become visible to the caller. You might want to think about whether you really want to pass
moneyanditemcostby reference here: