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.
Related
I'm currently working on an assignment and it's meant to take the concept of a car body shop offering different trim packages at different prices, the program is meant to use a pretest loop to stop the function if a user inputs a code that isn't already on the array, and then the user inputs the base price of their car and the program is meant to add the base price, the trim price and a 15% sales tax and give the new user their total cost. If I only had to create a function that displayed array's I think I'd have no trouble but I'm currently tearing my hair out trying to wrap my head around how to get all the different functions to work together
currently my algorithm is
1)enter the base price of car
2.) Enter the trim package code
3.) searchIndex=0
while OptionPackageCodeArray =[search index]
searchIndex++
end loop
if searchIndex<5
input packageCode
OptionPackageCode[searchIndex] = packageCode
else
Display error "This code does not exist"
end if
4.) Determine totalCost
PackageCostArray[searchIndex] + basePrice = costwithPackage
totalCost = costwithPackage*0.15
5.) display total cost
"The price of your car with Trim is" : totalCost
end loop
and the actual C++ I have written so far is
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare variables
double basePrice = 0.00;
string OptionPackageCodeArray[] = {"BB", "SP", "NP", "HE", "UC"};
double PackageCostArray [] = {1500.00, 3250.00, 4575.00, 7500.00, 5220.00};
double totalCost = 0.00
//prompt for base price
cout << "Enter base price:";
cin>>basePrice;
cout <<"enter package code: BB, SP, NP, HE, UC";
cin >> OptionPackageCodeArray;
}
however I'm stuck at this point
if anybody has any suggestions I'd be happy to take them.
you just write the code step by step. you can read blow code for reference.
double basePrice = 0.00;
static const int num = 5;
string OptionPackageCodeArray[num] = {"BB", "SP", "NP", "HE", "UC"};
double PackageCostArray [num] = {1500.00, 3250.00, 4575.00, 7500.00, 5220.00};
double totalCost = 0.00;
while(true)
{
//prompt for base price
cout << "Enter base price:";
cin>>basePrice;
std::string package;
cout <<"enter package code: BB, SP, NP, HE, UC"<<std::endl;
cin >> package;
int i = 0;
for (; i < num; i++)
{
if (OptionPackageCodeArray[i] == package)
{
break;
}
}
if (i == num)
{
break;
}
else
{
std::cout<<(basePrice + PackageCostArray[i]) * 0.15<<std::endl;
}
}
So, I have to do a homework problem that entails the following:
During the tax season, every Friday, J&J accounting firm privides assistance to people who prepare their own tax returns. Their charges are as follows.
a. If a person has low income (<=25,000) and the consulting time is less than or equal to 30 minutes, there are no charges; otherwise, the service charges are 40% of the regular hourly rate for the time over 30 minutes.
b. For others, if the consulting time is less than or equal to 20 minutes, there are no service charges; otherwise, service charges are 70% of the regular hourly rate for the time over 20 minutes.
(For example, suppose that a person has low income and spent 1 hour and 15 minutes, and the hourly rate is $70.00. Then the billing amount is 70.00 x 0.40 x (45 / 60) = $21.00.)
Write a program that prompts the user to enter the hourly rate, the total consulting time, and whether the person has low income. The program should output the billing amount. The program must contain a function that takes as input the hourly rate, the total consulting time, and a value indicating whether the person has low income. The function should return the billing amount. The program may prompt the user to enter the consulting time in minutes.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
const int HOUR = 60;
int minutes = 0;
double intake(payment);
void intake()
{
char income, y('y'), n('n');
cout << "Is the income rate over 25,000? Y - Yes | N - No): ";
cin >> income;
switch(income)
{
case 'n':
case 'N': low_procedure()
break;
case 'y':
case 'y': high_procedure()
break;
default: cout << "Invalid entry. You must indicate low or high income.\n"
break;
}
}
int main()
{
intake();
cout<<"You owe: \n";
cout<< payment <<endl;
}
double low_procedure()
{
const double LOW_DISCOUNT = 0.40;
const int LOW_TIME = 30;
consult = getConsultTime()
rate = getRate()
if consult > LOW_TIME
{
minutes = consult - LOW_TIME
result = rate * LOW_DISCOUNT
payment = calcPay
}
else
cout <<"No additional fees. \n";
return payment;
}
double high_procedure()
{
const double HIGH_DISCOUNT = 0.70;
const int HIGH_TIME = 20;
consult = getConsultTime()
rate = getRate()
if consult > HIGH_TIME
{
minutes = consult - HIGH_TIME
result = rate * HIGH_DISCOUNT
}
else
cout<<"No additional fees.";
}
int getConsultTime()
{
int consult = 0;
cout << "How long was the consult for in minutes? \n";
cin >> consult;
return consult;
}
double getRate()
{
double rate = 0.00;
cout << "What was the hourly rate? \n";
cin >> rate;
return rate;
}
double calcPay
{
double payment = 0.00;
payment = result * (minutes/HOUR);
return payment;
}
I've been having a lot of trouble here since I realized that I need to declare variables in code. I have a feeling I'm making this more complex than it needs to be, but the switch statement is important. I'm trying to sieve through bad, unimportant data.
You should declare them in the smallest scope that makes sense. Since you are apparently using them in multiple functions, the file scope (which is generally thought of as 'globally', not 'locally') seems appropriate.
As an alternative, you could make a class that has the variables and functions as members, but under the circumstances it seems overkill...
One way to do this is to group data into a struct, make a instance of that struct for each person, and make all functions accept a pointer or a reference of that struct and access its fields.
(When you learn classes then you can forget about this answer.)
There are a lot of reasons to avoid global variables (like namespace pollution).
Even if you limit them to file scope or namespace scope, there are still a lot of reasons to avoid variables with static storage duration (like thread safety, initialization order).
The rule of thumb is always "to use the smallest scope possible".
#include <iostream>
using namespace std;
struct AccountData {
int consult;
int minutes;
double rate;
double result;
double payment;
};
AccountData makeAccount(int consult, int minutes, double rate, double result, double payment)
{
return AccountData({consult, minutes, rate, result, payment});
}
void high_procedure(AccountData *thisAccount)
{
cout << "do something with the account, like printing out \"payment \""
<< thisAccount->payment
<< "\n";
}
void low_procedure(AccountData *thisAccount)
{
thisAccount->payment+=1.0;
cout << "do something with the account, like adding 1 to \"payment \""
<< "\n";
}
int main() {
AccountData account1 = makeAccount(1,2,3,4,5);
high_procedure(&account1);
low_procedure(&account1);
high_procedure(&account1);
AccountData account2 = makeAccount(10,20,30,40,50);
high_procedure(&account2);
low_procedure(&account2);
high_procedure(&account2);
return 0;
}
Demo:
https://ideone.com/sWVoHF
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.
I have wrote some basic code for a project. I am at the point I am trying to take an input from a RFID reader using a keyboard emulator. The follwing is my code to this point:
#include <iostream>
#include <ios>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
char product; //declaring the variable for the switch/case
int Pay = 0; //Declaring the variable Pay
int Payment = 0;
double Total = 0; // Declaring the Final Total variable
double Subtotal = 0; // Declaring the variable Subtotal
double Tax = 0; // Declaring the variable Tax
int m = 0; //counts the amount of times milk is scanned
int b = 0; //counts the amount of times beer is scanned
int c = 0; //counts the amount of times candy bar is scanned
int r = 0; //counts the amount of times rice is scanned
cout << "Scan the product you desire to purchase: \n";//Asking user to input product purchasing
cout << "When ready to checkout press the z button.\n\n\n"; //Telling user to press button z to pay
while(Pay < 1) //Keeps in the loop until pay is increased to 1
{
getline(cin, product); //Taking input and assining to the variable product
if(product == E007C02A55EF918D)
{
cout << "6 pack of Budlight...........$6.49\n"; // If the button b is pushed displays
Subtotal = Subtotal + Beer; // Calculates the Subtotal and stores it
Tax = Beer * Taxrate + Tax; // Claculates the total Tax and stores it
b++;
}
else if(product == E007C02A55EF937C)
{
cout << "Snickers Bar.................$0.99\n";// If the button c is pusehd displays
Subtotal = Subtotal + Candy_Bar;
Tax = Candy_Bar * Taxrate + Tax;
c++;
}
else if(product == E007C02A554A7A8B)
{
cout << "1 Gallon of 2% Milk..........$3.99\n";//If the button m is pushed displays
Subtotal = Subtotal + Milk;
m++;
}
else if(product == E007C02A55CE0766)
{
cout << "Box of Brown Rice............$2.79\n";//If the button r is pushed displays
Subtotal = Subtotal + Rice;
r++;
}
else
cout << "Invaild product. Please scan a different product.\n";
if (product == 'z')
Pay++; //When finished it increases pay to 1 to break the while loop
Total = Subtotal + Tax; // Claculates the Total
}
I am using MSVS 2010 to compile this code. With this code I can not compile because it says E007C02A55EF918D is undefined. E007C02A55EF918D is the serial number from one of the RFID tags and is what I am trying to input. I know I am having problems with the getline function also, but I am more worried about getting the serial number as an input.
char is big enough for a single character (it is usually an 8bit quantity, but don't rely on that).
So your product variable can only hold one char.
E007C02A55EF918D is an identifier (because it begins with a letter, it is not considered as a number, and because it is not quoted, it is not interpreted as a string).
If you intended product and those serial numbers to be 64bit numbers, you'll need to change product to be large enough to store them (uint64_t for instance), and change the serial numbers in your code to be numbers by prefixing with 0x. You'll also have to change your input method (getline takes strings, so you will need to convert that string to a number - see How to convert a number to string and vice versa in C++ for instance).
if (product == 0xABCD1234)
If you indented both to be strings, then declare product with:
std::string product;
and quote ("") the serial numbers. You'll also need to change the last test to:
if (product == "z")
^ ^
You can't compare an std::string with a single char ('z' is a char, "z" is a C-style 0-terminated string).
Try having it in "" and use strcmp() instead of ==, like
if (!strcmp("E007C02A55EF937C",product))
or
if (strcmp("E007C02A55EF937C",product)==0)
Hope it helped you.
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".