C++ mathematical issue - c++

So on my final project, a black jack and poker simulator using inheritance from a cards class, we have to keep track of the user's bet and total Money. However, in my code, it does very strange things. For example: if your total money was 1000000000 dollars and you bet 100 and won back 200 your new total money is now equal to 199 dollars
My program goes back and forth from doing this, and not doing this. It's maddening and I don't know why it's happening. The following is my main function, and my two functions that handle each poker game. If anyone thinks more code is needed to answer, though I'll gladly include class headers and implementation files. Thanks to all who may help! The following is my main functions, and the two functions to handle each game:
unsigned int handlePoker(unsigned int);
unsigned int handleBlackJack(unsigned int);
//main function:
//asks the user what game they want to play
//then calls a function for the appropriate
//game chosen
int main()
{//two choices:
//one for quitting the program
//the other for whichever game they want
char yesOrNo;
char choice;
unsigned int totalMoney;
cout<< "please enter a starting amount to bet with"<<endl;
cin>>totalMoney;
cout<<"would you like to play?"<<endl;
cout<<"enter 'y' for yes and 'n' for no"<<endl;
cin>>yesOrNo;
do{
//ask the user which game they want
cout<<"would you like to play poker or black jack?"<<endl;
cout<<"input '1' for poker and '0' for blackjack"<<endl;
cin>>choice;
if(choice == '1')
{
totalMoney = handlePoker(totalMoney);
}//end if
else if(choice == '0')
{
totalMoney = handleBlackJack(totalMoney);
}//end else if
else
{
cout<<"I'm sorry, the input you entered was invalid"<<endl;
cout<<"please try again"<<endl;
cin.clear();
}//end else
cout<<"would you like to try again?"<<endl;
cout<<"('y' for yes, or 'n' for no)"<<endl<<endl;
cin>>yesOrNo;
}while(yesOrNo == 'y' || yesOrNo == 'Y'); //end do while loop
return 0;
}//end int main
//handle poker:
//a void function which takes an
//unsigned integer value
//the function declares a "poker" object
//and uses it's void functions to sim a poker game
unsigned int handlePoker(unsigned int tot)
{
unsigned int multiply;
unsigned int betMonies;
unsigned int win;
poker round;
cout<<"how much do you want to bet?"<<endl;
cin>>betMonies;
//if the bet money entered was valid
// we begin playing
if(betMonies < tot)
{//big if begin
//ask if they want a better hand
round.betterHand();
//set the number we multiply your money by
multiply = round.rewardMoney();
//if multiply is 0
//then the user has lost this hand
//we inform them as such, and subtract
//their bet money from their total money
if(multiply == 0)
{
cout<<"I apologize, but you seem to have lost"<<endl;
cout<<"when you lose, your bet is subtracted"<<endl;
cout<<"your initial balance was: "<<tot<<endl;
//decrement the total
tot = (tot - betMonies);
cout<<"your new balance is: "<<tot<<endl;
}//end if
//if multiply is not 0 (assuming it's not negative
//because there's no way it could be)
//we tell them what they've won, and add it to
//their total money
else
{
win = (multiply*betMonies);
cout<<"your initial balance was: "<<tot<<endl;
cout<<"your win was"<<win<<endl;
//increment the total
tot = (win + tot);
cout<<"your new balance is "<<tot<<endl;
}//end else
}//big if end
//if the amount entered was not valid
//simply tell them, then run the loop again
else
{//else begin
cout<<"I'm sorry, that was not a valid amount of money"<<endl;
cout<<"please try again"<<endl;
}//end else
round.shuffleDeck();
return tot;
}//end handlePoker
//handle Black jack:
//a function returning an unsigned int
//that keeps track of the total money
//declares a black jack object
//and uses it's member functions to play black jack
unsigned int handleBlackJack(unsigned int tot)
{
blackJack play;
unsigned int reward;
unsigned int betMoolah;
//ask the user for the bet they want
cout<<"how much do you want to bet?"<<endl;
cin>>betMoolah;
//if the bet is less than the total passed by reference
//then we can start running the game
if(betMoolah < tot)
{
//print the hands dealt in the constructor
play.printHands();
//run the function that lets them hit or stay
//the function contains a do while loop
// so, no looping is required
play.hitOrStay();
//we then handle the reward
//which returns an integer type
reward = play.handleReward(betMoolah);
//prints dealer and player's hands fully
play.printHandGame();
//in one of the cases, reward is set to -1
//we use this here:
if(reward < 0 )
{
//if the reward is negative, then
//we subtract the bet money
//then we tell the user their new balance
cout<<"your balance was "<<tot<<endl;
cout<<"you have lost, so your bet is subtracted"<<endl;
tot = (tot-betMoolah);
cout<<"your new balance is: "<<tot<<endl;
}//end if
//if the reward is above 0, then we add the reward to the total
else if(reward > 0)
{
cout<<"your original balance was "<<tot<<endl;
cout<<"your winnings are: "<< reward<<endl;
tot = reward + tot;
cout<<"your new balance is: "<<tot<<endl;
}//end else
else
{
cout<<"you have lost no money"<<endl;
cout<<"your balance is still " <<tot<<endl;
}
}//end of the big if
//if the amount of money entered is above total money
//then the money entered isn't valid at all
else
{
cout<<"the amount of money you've entered is not valid"<<endl;
cout<<"please try again"<<endl;
}// end else
play.shuffleDeck();
return tot;
}//end handleBlackJack

I can't fully explain what your seeing, but I did notice a liberal use of unsigned int. In particular, in handleBlackJack you have:
unsigned int reward;
and then
reward = play.handleReward(betMoolah);
and finally
if(reward < 0 )
If reward can be negative, it shouldn't be an unsigned int. As others have suggested, step through it in a debugger and "follow the money".

Related

Why is my do/while loop in c++ not allowing me to input 'amount' more than once?

I am attempting to develop a vending machine in C++ in which the user can insert as many 50 cent, 20 cent, and 10 cent coins as they would like to then move on to the 'purchase' of a product.
So far, my primitive code runs smoothly; the issue I am currently facing is that I can only 'insert' coins into the vending machine once, even though I think the 'while' condition in the 'do/while' statement is being executed.
Below you can find my code:
`
#include <iostream>
using namespace std;
int main() {
int productid;
string order, finished;
int amount;
cout << "Welcome to the coffee machine! We have a variety of beverages we can offer. \n Here is our selection: \n 1) Coffee- 50 cents \n 2) Tea- 60 cents \n 3) Cappuccino- 80 cents\n";
cout << "Please select your drink of choice by entering its ID: (1, 2, or 3)";
cin >> productid;
if (productid != 1 && productid != 2 && productid != 3){
cout << "That is an invalid entry; please try again. \n";
cin >> productid;
}
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
cin >> amount;
if (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
cin >> amount;
}
do {
amount += amount;
}
while (amount != 0);
return 0;
}
`
I was expecting to be able to insert coins until I input '0', but the code terminal says 'Process finished with exit code 0' after I insert coins once, thereby not allowing me to continue to insert coins.
If anyone has any suggestions as to how I could fix this so that the user can continuously insert coins until they input '0' I would greatly appreciate it.
Please feel free to leave any suggestions as to how to proceed as well.
Thank you
Your do-while looks like this:
do {
amount += amount;
}
while (amount != 0);
What does this do? It adds amount to itself until eventually it is 0. This can happen due to the fact that numbers are stored in a finite number of bits in memory and when due to some operation (value assignment in this case) is greater than the maximum value that can be stored for the given type, then the value will overflow its type limits and may get a smaller value than prior to the addition as a result, maybe even 0.
However, this is definitely not what you want.
You want: to read amount repeatedly until it's 0 and add it to a sum
You actually do: read amount exactly once, then add it to itself until it's 0
How to remedy this:
Move the reading inside the code and make sure that the sum will be a different variable:
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
int sum = 0;
do {
cin >> amount;
if (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
} else {
sum += amount;
}
}
while (amount != 0);
You need to put the do { ... } while(...); around the entire block you'd like to repeat. Also, you need a separate variable for the sum.
int amount, sum = 0;
// ...
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
do {
cin >> amount;
while (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
cin >> amount;
}
sum += amount;
}
while (amount != 0);
I've also changed an if to a while in your code for the case when the user makes multiple mistakes.
To solve these cases yourself, it's recommended that you either use a debugger and step through your code; or add some logging into the code an check what's going on (e.g., what the loop repeats).
the reason why the program does not ask you for another input is because the do-while loop only includes one line: amount += amount;
Also this is the issue why the program terminates, it gets stuck in this loop of adding amount on itself and when the int overflow happens and the amount gets zero value, the program terminates. You can check this behavior by printing out the amount variable in the loop.
amount += amount;
cout << amount << endl;
To fix the issue, you need to move couple of lines inside do block.
do {
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
cin >> amount;
cout << amount << endl;
if (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
cin >> amount;
}
amount += amount;
cout << amount << endl;
}
while (amount != 0);
Also, you need one more variable for the sum of coins (amount). This way if you add only one coin, the amount variable will be doubled.
Hope this helps.

GPA calculator crash bug in c++

I am a noob in programming and was told that to learn more, I need to do some project and so I started this GPA calculator that eventually prints your GPS in both 5 unit and it 4 unit equivalent.
The problem is I created an array to hold the grade point from A-F and another array to hold the letter grade from 0-5, but after I was done it performed well until I noticed it crashes when I try to calculate for more than 6 courses, I have tried what I can do but still can't detect the bug and solve the problem all to no avail.
#include<iomanip>
#include <iostream>
using namespace std;
int main(){
int numOfCourse;
cout<<"insert the number of courses offered: ";
cin>>numOfCourse;
int scores[numOfCourse];//an array that stores the number of course inputed by the user
int creditUnit[numOfCourse];//another array that stores the credit unit of the user
int qualityPoint[numOfCourse];//this is gotten by multiplying the credit unit by grade point
int totalQualityPoint=0;
int totalCreditUnit=0;
int gradePoint[6];//predefined grade point 0-5
string letterGrade[6];//predefined letter grade A-F which corresponds with the grade point
float gradePointAverage5;//5 point GPA Scale
float gradePointAverage4;// 4 point GPA Scale
// Asks the user to input scores and credit load of the courses
for (int i=0; i< numOfCourse; i++){
cout<<"input the scores of the course: ";
cin>>scores[i];
cout<<" input the credit load of the course: ";
cin>>creditUnit[i];
//defining the gradepoint and its corresponding letter grade
if(scores[i] <= 39){
gradePoint[i]=0;
letterGrade[i] = "F";
} else if (scores[i] >=40 && scores[i] <= 44){
gradePoint[i]=1;
letterGrade[i] ="E";
} else if (scores[i] >=45 &&scores[i]<= 49){
gradePoint[i]=2;
letterGrade[i] = "D";
}else if (scores[i] >=50 &&scores[i] <= 59){
gradePoint[i] =3;
letterGrade[i] = "C";
}else if (scores[i] >=60 &&scores[i] <= 69){
gradePoint[i]=4;
letterGrade[i] = "B";
}else if (scores[i]>=69 &&scores[i] <= 100){
gradePoint[i]=5;
letterGrade[i] = "A";
}else{
cout<< "Your grade is incorrect"<<endl;
return 0;
}
}
cout<<"Scores Letter Credit Grade QualityPoint"<<endl;
cout<<" Grade Unit Point (CU * GP)"<<endl;
for(int i =0; i<numOfCourse;i++){
qualityPoint[i] = creditUnit[i] * gradePoint[i];
cout<<scores[i] <<" "<<letterGrade[i]<<" "<<creditUnit[i]
<<" "<<gradePoint[i]<< " "<<qualityPoint[i]<<endl;
totalQualityPoint=totalQualityPoint + qualityPoint[i];
totalCreditUnit=totalCreditUnit + creditUnit[i];
gradePointAverage5= float(totalQualityPoint)/float(totalCreditUnit);
gradePointAverage4 = (gradePointAverage5/5)*4;
}
cout<< "Your total Quality Point is: "<<totalQualityPoint<<endl;
cout<< "Your total Credit Unit is: "<<totalCreditUnit<<endl;
cout<< "Your Grade Point Average (GPA) on the 5 point scale is : "<<setprecision(2)<<fixed<<gradePointAverage5<<endl;
cout<< "Your Grade Point Average (GPA) on the 4 point scale is : "<<setprecision(2)<<fixed<<gradePointAverage4<<endl;
}

Using do while loop and while loop to write a program that will run random guessing game...i stuck at the do while loop

I have been run a random guessing game. The game secret numbers is from min to max that input by user, the guesser is ask guess the secret number and at the end is supposed to be asked if they would like to play again. There also has to be multiple options for print outs if the guesser is to high or low. Anyways, I want it to check and make sure that the user is inputting numbers, not something silly. So I have been going in circles trying to figure this part out. I am sure it is a easy fix, but I am new to programming and this has got me stumped. Any help would be appreciated.
my code should similar to below output images :
[1]http://i62.tinypic.com/wjvuqb.png
[2]http://i57.tinypic.com/2nq9jwm.png
[3]http://i62.tinypic.com/210zss7.png
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int min, max, secret=0, deposit, bet, guess;
bool again= true;
string name;
char reply;
cout<< setw(80)<< setfill('=')<<"\n\n";
cout<< setw(45)<< "NUMBER GUESSING GAME!"<<"\n\n";
cout<< setfill('=')<< setw(80)<<"\n\n";
cout<< "What ur name?\n";
getline(cin,name);
Again:
cout<< "Pls enter the min & max number\n";
while(!(cin>>min)||min<0)
{
cout<<"Min? ";
cin.clear();
cin.ignore();
}
while(!(cin>>max)||max<0)
{
cout<<"Max? ";
cin.clear();
cin.ignore();
}
while(!(max> min))
{
cout<<"Min is larger than Max\n";
goto Again;
}
cout<< "\nMin: "<<min<<"\nMax: "<<max<<"\n";
secret= rand() % max+min;
cout<<"Enter ur deposit: ";
cin>> deposit;
AA: cout<< setw(45)<< "\n\n\n\nRULES OF THE GAME"<<"\n\n";
cout<< setfill('-')<< setw(80)<<"\n\n";
cout<< "Guess number between "<< min<< " to "<< max;
cout<< "\nIf ur guess match, 10 times ur deposit!!";
cout<< "\nIf ur guess mismatch, lose ur betting amount!!";
cout<< "\n\n"<< setfill('-')<< setw(80)<<"\n\n\n";
cout<< "Current Balance: "<<deposit;
cout<< "\nWhat is ur betting amount? ";
cin>> bet;
do{
cout<< "\n\nEnter a guess to bet: ";
cin >> guess;
if (guess > max)
{
cout << "Too high!\n\n";
cin.clear();
cin.ignore();
}
else if (guess < min)
{
cout << "Too low!\n\n";
cin.clear();
cin.ignore();
}
}while (guess != secret);
if(guess != secret){
deposit-=bet;
cout << "\nThat's it! You got it!\n";
cout<<"Sorry, U lose RM "<< bet;
}
else{
bet*=10;
deposit+=bet;
cout << "\nThat's it! You got it!\n";
cout<<"Congratulation! U earn RM "<< bet;
}
cout<<"\n\nThe secret number was : "<< secret;
cout<< "\n\n\tCurrent Balance: "<<deposit<< "\n\n\n";
do{
cout<< "Wanna play again (y/n)? ";
cin>> reply;
if( reply=='y'){
again= true;
goto AA;
}
else
cout<<"\nReally? Ok, try again! ";
cin>>reply;
}while(again==false && reply=='n');
if(reply=='n'){
cout<<"\n\n\n"<< setw(80)<< setfill('+')<<"\n\n";
cout<< setw(30)<< "THX FOR PLAYING! UR CURRENT BALANCE IS RM "<< deposit<<"\n\n";
cout<< setfill('+')<< setw(80)<<"\n";
}
return 0;
}
You are using goto, and if you are using goto, raptors will tear you to pieces. Do not, under any circumstances use goto!
But you can use functions to make your code a bit clearer. This wall of text and copy paste is really hard to read.
First of all the formula you are using to calculate the random number is wrong. Suppose that min is 10, and max is 12. Then the rand() % max could be, let's say, 10. Adding min (10), the number to guess would be 20 - far greater than max... It should be secret = rand() % (max-min +1) + min; (if your interval is [min, max]).
Now to your question - as far as I understood you want to know if the entered guess is a number. Here is what you can do:
while(1)
{
cin >> guess;
if(cin){
if (guess > max){
cout << "Too high!\n\n";
cin.clear();
cin.ignore();
continue;
}
else if (guess < min){
cout << "Too low!\n\n";
cin.clear();
cin.ignore();
continue;
}
else if(guess != secret){
deposit-=bet;
cout<< "Sorry, U lose RM "<< bet;
}
else if(guess == secret){
bet*=10;
deposit+=bet;
cout<< "\n\nCongratulation! U earn RM "<< bet;
}
break;
}
else
{
cin.clear();
cin.ignore();
cout << "Error! You did not enter a number!" << endl;
continue;
}
}
If the user didn't enter a number, the cin's fail flag will be up and you can use that.
Also, when trying again (goto AA;) you do not compute the random value again and you should. In order to get a different sequence of random numbers from rand() every time you start the program, you should seed the random generator from the current time. In the beginning of main, put srand((unsigned int)time(NULL)); What this does is that it gives the random generator a number and on its base it will generate random numbers. If the number is the same every time the program is started, the same numbers will be generated. But given the always changing current time, every time the sequence will be different.
Using goto can make your code very messy and can make bugs very hard to notice. Yes, it is a part of the language and it is there to be used, but one should be very careful with it. Especially if you are new to programming, try to refrain from using it. You could use while(1) or for(;;) if you need endless loops - you can get to the next iteration with continue; and stop them with break;.
Something is also wrong with the guessing loop. It seems that you cannot lose. You should decrease the deposit in the while loop and check if it is 0.
Edit: In the edited code you can see that whenever the user needs to enter the number again, you just skip the iteration with continue. This is also an example how you should deal with endless loops instead of using goto. With practice, you will get he hang of it. ;)
Edit 2:
do{
cout<< "Wanna play again (y/n)? ";
cin>> reply;
if( reply!='y'&& reply!='n')
cout<< "\nReally? Ok, try again! \n";
}while(reply!='n' && reply!='y');
if( reply =='y')
goto AA;
if(reply=='n'){
cout<< "\n\n\n"<< setw(80)<< setfill('+')<< "\n\n";
cout<< setw(30)<< "THX FOR PLAYING! UR CURRENT BALANCE IS RM "<< deposit<< "\n\n";
cout<< setfill('+')<< setw(80)<< "\n";
}
This should make the reply cycle work. Your program should consist of different chunks of code for different purposes, and in this cycle you mixed up checking the correctness of the answer with what will happen if the answer is correct. It's easier first to do the first, and then to do the second thing. Using functions can generally help you with this.
Edit 3: In that new code you have a lot of problems with if statement. Firstly, what is !> ? I think you meant < or <= , !> does not exist, it won't even compile. Another thing - what happens when max or min is 0? You haven't covered that.
You use if-else chains a lot and in this case it is not necessarily needed. For example you don't need if(min>0) , you don't even need the else before it. If you don't enter one of the if statement - the input is correct and you can break, if you enter one of them - it has continue; in it and the code below is not executed. The same goes for the last if statement in the max if-else chain executed if the input is a number.
Anyway, you could do it a lot simpler. For example the min loop can be:
cout << "Pls enter the min of secret number\n";
while (!(cin >> min) || min<=0){
cout << "Pls enter the min of secret number\n";
cin.clear();
cin.ignore();
}
You could see that this will work if you realize that you should break if (cin && min>0). Now when you negate that in order to place it as the while condition it becomes (!cin || min<=0).
Anyway, I didn't see any other problem in the code, I tested it and it worked. And now without goto it looks a lot better.

Simple program - menu is being displayed only once

I am trying to keep a track of total amount of bought groceries.
In my program, every time I buy apples, cheese, or bread, the program should continue with displaying the menu again.
But it keeps asking "How many apples?" after the program has already calculated the total for the apples instead of going back to the menu to choose another item.
Perhaps it has something to do with the type of loop I have used.
I am stuck on trying to figure this out. Any help would be appreciated.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
double BUDGET;
const double apple= .60;
const double lb_cheese= 1.60;
const double loaf_bread = 2.50;
double total;
int count;
char choice;
double amount_left;
cout <<"Welcome! What is the budget for your picnic lunch?"<< endl;
cin>> BUDGET;
cout<<"Choose one of the following"<<endl;
cout<<"-------------------------------------"<<endl;
cout<<" MENU \n "<<endl;
cout<<"A-Apple B-Cheese C-Bread"<<endl;
cout<<" $0.60 $1.50 $2.50 "<<endl;
cout<<"-------------------------------------"<<endl;
cin>> choice;
while ((choice != 'Q') && (total <BUDGET)) //Q is the sentinel value to "quit" the program
{
switch(choice)
{
case 'A':
case 'a':
cout<<"How many apples?";
cin>> count;
total+= (count *apple);
break;
case 'B':
case 'b':
cout<<"How many pounds of cheese ?";
cin>> count;
total+= (count* lb_cheese);
break;
case 'C':
case 'c':
cout<<"How many loafs of bread?";
cin>> count;
total+= (count * loaf_bread);
break;
default:
cout<<"The entry you have entered is not valid, please try again."<<endl;
}
if( total > BUDGET)
{ cout<<"You have exceeded your budget please check your cart.\n\n";
break;
}
cout<<"Your total is: $"<<setprecision((2))<<fixed<<total<<endl;
amount_left= BUDGET-total;
cout<<"You have $"<<setprecision(2)<<fixed<<amount_left<<" left to spend."<<endl;
}
return 0;
}
Displaying menu is out of the loop:
display menu
read option
while (option != quit) {
do some calculations
}
and the menu is therefore displayed only once. You could change it to infinite loop:
while (true) {
display menu
read option
if (choice == 'Q' || total >= BUDGET)
break;
do some calculations
}
Also try to avoid writing functions that are longer than 50 lines, place some logic into some different function and just call this function, decompose it to smaller parts, it will be much easier to read and also much easier to understand.
Yes, get the menu in a loop to display it the number of times you desire and also please remember to initialize your variables as good practice.
Double total=0.00 // initialize.

Wrong values with division

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;
}}
void howmany(double &money, double &itemcost)
{
double items;
items = money / itemcost;
itemcost = itemcost * items;
money = money - itemcost;
}
Mathematically, this function will always return zero: itemcost = itemcost * (money / itemcost) always evaluates to money (to a numerical error). Therefore money - itemcost equals 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 money and itemcost by reference here:
void howmany(double &money, double &itemcost)
howmany never communicates items back to its caller in any way, so there's no way it could print out. I'm also unable to quickly verify that it's doing the right thing.
Then, when you call howmany you print out cash as the number of items and item as the cash remaining which also appears wrong. There may be other bugs.
You should take a long hard look at the code, and start stepping through one code path at a time.
I believe you may need to hit 'Q' once for each call to menu.
I don't see the need for 3 of them.
In the do-while loop, you call menu without checking the return value. You need to press a letter for this one, so you enter 'Q' and nothing happens.
The program then encounters a second call to menu, this time placing the return value in a variable. So you enter a 'Q' here.
The do-while loop is terminated, but another call is made to menu. It prompts you again and so you enter a Q, a third time.
You need to decide whether to let the menu function display and received data OR split the functionality into a displayer and a data retriever. The first call to menu indicates this logic. Whatever you decide, be consistent throughout your program.