am i on the right track? Cashier Program C++ - c++

I'm new to C++ and was wondering if i was on the right track? I'm kind of confused about this but was hoping for possibly some helpful hints on things i am missing/ have wrong....i know its not completely finished i still need to do the breakdown of the dollars,quarters....etc
Question: A cash register uses an automated coin machine to help make change. We assume that a clerk is handed money to pay for purchases. For change, the clerk returns to the customer any paper money and directs the coin machine to distribute any changes less then $1. In this exercise, you are to simulate the action of the clerk and the machine.
At the cash register, we need access to the purchase price and the payment. The change, which is the difference between the payment and the purchase prices, is a real number. The whole part represents the change in dollars and the fractional part is the change in cents that is returned in quarters, dimes, nickels, and pennies. For instance, with a payment of $10 to cover purchases of $3.08, the required change is $6.92. The clerk hand out $6 and the coin machine distributes 3 quarters, 1 dime, 1 nickel, and 2 pennies for the 92 cents.
92 = 3(25) + 1(10) + 1(5) + 2
Use real-number objects that identify the purchase price (price), the amount of payment (payment), and the change (change). The main program computes the amount of change (coinChange) and partitions it into dollars (dollars), quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies).
You must declare constants for quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies). You must use compound operators in the calculations. You must use setreal(w,p) and setw(n) for the output.
What I have done so far:
// Me
// A BRIEF PROGRAM DESCRIPTION FOR CHAPTER 2, HOMEWORK 4
// COMMENT THE PREPROCESSOR
#include <iostream.h>
// COMMENT THE PREPROCESSOR STATEMENT
#include "textlib.h"
int main( )
{
// COMMENT THE CONSTANTS
const int QUARTER_AMOUNT = 25;
const int DIME_AMOUNT = 10;
// COMMENT THE OBJECTS
double price;
double payment;
double change;
int numofDollars;
int numofQuarters;
int numofDimes;
int numofNickles;
int numofPennies;
int coinChange;
cout << "Enter the purchase total: ";
cin >> price;
cout << "Enter the payment: $";
cin >> payment;
// COMMENT THE CALCULATION
change = payment - price;
numofDollars = int(change);
coinChange = (int((change / numofDollars) * 100));
numofQuarters = coinChange / 25;
coinChange = coinChange / (numofQuarters * 25);
numofDimes = coinChange / 10;
numofNickles = coinChange / 5;
numofPennies = coinChange / 1;
// OUTPUT THE INFORMATION
return 0;
}

Yes, you are on the right track. Your general structure is sound. These sorts of homework assignments almost always have a structure like this:
int main () {
// read in the data
...
// Do the math
...
// Write out the data
...
}
You do have some math errors. Try stepping through the code with a pencil and paper, pretending that you are the computer. Also, try stepping through the code with your debugger, examining the variables after each line. Compare what actually happened to what you expected.

Related

How do I make my program stop having build issues and make it stop using negative numbers? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My program needs to be able to calculate the monthly phone bill and there are 3 plans: Basic where 10 hours are free and it costs 9.95, Gold where 20 hours are free and it costs 14.95, and Platinum where you have unlimited hours and it costs 19.95. When my program is given hours less than the free hours it subtracts them from the initial cost, and also it has build hours.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Set up the variables.
string input;
int hours;
int basicHours;
int goldHours;
float extraBasic;
float basicCost;
float goldCost;
// Will ask and display the user their plan and hours.
cout << "Hello! Welcome to the Comms4You Telecom Company!" << endl;
cout << "Please provide your plan." << endl;
cin >> input;
cout << input << ", Ok now please provide the amount of hours you used." << endl;
cin >> hours;
//Calculate different equations
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
//This part is for displaying to the users plans and hours.(Also calculations)
if (input == "Platinum") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $19.95.";
}
else if (input == "Gold") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << goldCost << ".";
}
else if (input == "Basic") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << basicCost << ".";
}
else
return 0;
}
The problem is in these lines:
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
Think about what they are doing.
basicHours = (hours - 10);
If hours was 11, then basicHours is now 11 - 10 = 1. This is good. But if hours was 9, then basicHours is now 9 - 10 = -1. This is not what you want; if I used less than my 10 free hours, then you want basicHours to be 0.
So you can write instead:
if (hours > 10) {
basicHours = hours - 10;
}
else {
basicHours = 0;
}
or equivalently:
basicHours = (hours > 10) ? hours - 10 : 0;
goldHours = (20 - hours)
This should be the exact same thing as basicHours, except with 20 instead of 10! I will let you adapt the above code.
basicCost = (9.95 + extraBasic); and goldCost = (14.95 + goldHours);
This is wrong. 9.95 is a monetary value, say in euros. extraBasic is a time, in hours. You cannot add hours with euros! If I used 12 hours with the basic plan, what is the result of 9.95€ + 2h? I do not know, it does not make sense.
If I used 12 hours with the basic plan, then I have to pay 9.95€, and I have to pay for the extra 2h. What is the cost of the extra 2h? It is 2 times the cost of an hour; in other words, it's the extra time multiplied by the hourly rate. You should have a constant variable called hourlyRate or basicHourlyRate in your program, with that value. Then you can write:
basicCost = 9.95 + extraBasic * basicHourlyRate;
goldCost = 14.95 + goldHours * goldHourlyRate;
Coding style: separate data and code
A good rule to follow is never to put data in your code. All literal values are data. The cost of the basic and gold and platinum plans are data. The hourly rate is data. The number of "free" hours for each plan is data. Define a few variables with explicit names, initialize those variables with the data at the very beginning of the code, then write the rest of the code without ever using a literal value. There are two reasons why this is important.
The code will be easier to read with variables. Explicit names in variables make the code meaningful; if you use literal values inside the code, the people reading your code don't know what those values stand for. Why do you subtract 10 from hours? We have to think about where this 10 comes from. However, if you write basicPayingHours = hours - freeBasicHours, we understand immediately. "The people reading your code" include StackOverflow members you're showing your code to, but also your schoolmates or coworkers, your teacher or boss, and most importantly, yourself when you read your code again six months from now.
When the data changes, it will be a lot easier to update your code if data is cleanly separated from code. Imagine you are working for this phone company. Next year, they update their plans and the basic plan is now 9.99 per month instead of 9.95. If this value is stored at the beginning of your code in a line basicPlanInitialCost = 9.95;, it is very easy to update it. However if there are multiple occurrences of 9.95 in your code, you will have to track them and change them all manually - this process is very prone to errors for two reasons: you might accidentally change the cost of something else that also costs 9.95; you might forget to update values that are dependent on the monthly price of the basic cost (like the yearly price of the basic cost, which is 12 * 9.95 = 119.40).

How to calculate the same accumulated amount

im trying a code to calculate accumulated/incremented amount of specific value.
for (int a=1; a<= qtydrink; a++)
{
cout << "enter drink name:"
cin.getline( drink, 15)
.......
if (strcmp(drink, "beer") == 0)
{
payment = 10.00;
.......
oke so one beer would cost 10$, but if the user input another beer, will it add or replace or something? i have an amount of 1.20 and user inputs it twice, amounting to 2.40 but in the output its just 2.20 sometimes.
i have 2 for loops. one for food and one for drinks. each time user can input different types of foods or drinks with different payments. i have to total up both food and drink's payment in the end plus tax.
please elaborate.
On the assumption that you are using payment as your output, that would be because you are setting the payment to be equal to 10.00, rather than incrementing it. To perform the increment, use += instead of =
EDIT: Everything you need to know about operators can be found here

C++ Decrementing and displaying active equations

I'm looking at figuring out this program for a lab, I have been working on it for a while now, but cannot for the life of me figure out how this works.
The objective is to display an active equation as it decrements from from the initial value.
For example:
20000.00 + 83.33 - 150.00 = 19933.33
19933.33 + 83.06 - 150.00 = 19866.39
19866.39 + 82.78 - 150.00 = 19799.17
19799.17 + 82.50 - 150.00 = 19731.66
19731.66 + 82.22 - 150.00 = 19663.88
19663.88 + 81.93 - 150.00 = 19595.81
19595.81 + 81.65 - 150.00 = 19527.46
And so forth. I have to display that as an output on the screen. But am not sure how to keep a decrementing total like that and how to display it as an active equation like that in cout form.
The number on the far left is an initial loan that a user inputs, the number in the middle is the interest rate which is calculate using p*r/p (initial loan * interestrate(user will input this as well)/ initial loan). And the number on the right just before the equal sign is a payment which the usual will enter.
The goal is to get it to perform 10 iterations or once the initial loan is fully paid off whichever comes first.
Here is a little guidance
Finance
First you got your basics wrong. If this is finance and it looks this way :-), p*r/p is crap.
The second column in your plot is not a rate, neither is it an interest rate, it is an interest.
P is the loan ammount
r is an annual interest rate
The interest is calculated using P times r/12 since the payments you show are monthly in case r is entered mathematically (e.g. 0.05 for 5 %) or P*r/1200 in case r is counterconventional entered as percentage.
C++
The input of the parameters could be done e.g.
double P, r, q;
std::cout << "Enter P, q and r:\t";
std::cin >> P >> r >> q;
you will need to have the numbers printed fixed precision, this can by done with
std::cout << std::fixed << std::setprecision(2)
one last hint: The needed include files will be
#include <iostream>
#include <iomanip>
last you will need a loop have a look for for-loops or do-while loops.
This should help you to get your homework a good start.

Using pointers in class

Hi all I have an unusual problem here. I wrote a moneychanger class that determines the number of bills and coins that are given as change, based on the total amount for a purchase and the amount of money given for the purchase. For example if you were going to buy something for $12.04 and gave a $20 dollar bill you would receive $7.96 in change.
the output would be:
0 twenty dollar bill(s)
0 ten dollar bill(s)
1 5 dollar bill(s)
2 1 dollar bills(s)
3 quarter(s)
2 dime(s)
1 penny(s)
now the thing is that i have to return the numbers of each bill and coin using pointers or references.
my program has two functions a GetBills which uses pointers to integers to return the number of $20, $10, $5, and $1 bills that are needed for the change.
the other is a GetCoins which again uses pointers to integers to return the number of quarters dimes, nickels, and pennies that are needed for the change.
My problem is this. my GetBills is not storing any values in the pointers but my GetCoins is. if i enter 12.04 for purchase price and 20.00 given amount
my output is:
0 twenty dollar bill(s)
0 ten dollar bill(s)
0 5 dollar bill(s)
0 1 dollar bills(s)
3 quarter(s)
2 dime(s)
1 penny(s)
so as you can see some the values for the coins good but not for the bills. What could be causing my pointers in my GetBills to not store the proper values?
here's my shortened code:
MoneyChanger.h
class MoneyChanger
{
private:
double amountP, amountG, totalChange;
int twenty, ten, five, one, change;
int quarter, dime, nickel, penny;
public:
void GetBills(int *twenties, int *tens, int *fives, int *ones);
void GetCoins(int *quarters, int *dimes, int *nickels, int *pennies);
};
MoneyChanger.cpp
void MoneyChanger::setData(double pp, double given)
{
amountP = pp;
amountG = given;
CalcChange();
}
void MoneyChanger::CalcChange()
{
while(totalChange >= 20){totalChange = totalChange-20; twenty++;}
while(totalChange >= 10){totalChange = totalChange-10; ten++;}
while(totalChange >= 5){totalChange = totalChange-5; five++;}
while(totalChange >= 1){totalChange = totalChange-1; one++;}
while(totalChange >= .25){totalChange = totalChange-.25; quarter++;}
while(totalChange >= .10){totalChange = totalChange-.10; dime++;}
while(totalChange >= .05){totalChange = totalChange-.05; nickel++;}
while(totalChange >= .01){totalChange = totalChange-.01; penny++;}
}
double MoneyChanger::GetTotalChange()
{
totalChange = amountG - amountP;
return totalChange;
}
void MoneyChanger::GetBills(int *twenties, int *tens, int *fives, int *ones)
{
*twenties = twenty;
*tens = ten;
*fives = five;
*ones = one;
CalcChange();
}
void MoneyChanger::GetCoins(int *quarters, int *dimes, int *nickels, int *pennies)
{
*quarters = quarter;
*dimes = dime;
*nickels = nickel;
*pennies = penny;
CalcChange();
}
Main.cpp
int main()
{
MoneyChanger mc;
int twenties, tens, fives, ones, quarter, dimes, nickels, pennies;
double purchase, given;
cout<<"please enter total cost of purchase: ";
cin>>purchase;
cin.ignore();
cout<<"\nplease enter amount given: ";
cin>>given;
mc.setData(purchase, given);
cin.ignore();
cout<<"Your change is: "<<mc.GetTotalChange()<<"\n\n";
mc.GetBills(&twenties, &tens, &fives, &ones);
mc.GetCoins(&quarter, &dimes, &nickels, &pennies);
cout<<twenties<<" twenty dollar bill(s)"<<endl;
cout<<tens<<" ten dollar bill(s)"<<endl;
cout<<fives<<" five dollar bill(s)"<<endl;
cout<<ones<<" one dollar bill(s)"<<endl;
cout<<quarter<<" quarter(s)"<<endl;
cout<<dimes<<" dime(s)"<<endl;
cout<<nickels<<" nickel(s)"<<endl;
cout<<pennies<<" penny(s)"<<endl;
return 0;
}
I think your problem is in GetBills and GetCoins the CalcChange function should be called first, before assignment. Assuming you've initialized your bills/coins member variables to 0, the first call to GetBills will set all the passed in bills to 0. Your function will then compute what the values of bills and coins should be. In call to GetCoins the coin member variables will have already been set to the correct values from the CalcChange call in GetBills.
I would recommend pulling calcChange out of both of those functions (as multiple calls to it is redundant) and do some thing like this in your main:
cout<<"Your change is: "<<mc.GetTotalChange()<<"\n\n";
mc.calcChange();
mc.GetBills(&twenties, &tens, &fives, &ones);
mc.GetCoins(&quarter, &dimes, &nickels, &pennies);

How do I use getline and stringstream to parse formatted date and time input?

I have only been working on c++ for about a month. I am not really understanding how it works, however I need to write a program for school. I used a void function and it seems to be working so far,but I have no idea what to do next I am lost at line 44, I am not sure how to make it work, is there a way to take a value from a certain string? If the value is in both strings how would I determine which value? Here is my assignment:
A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. People who park their cars for longer than 24 hours will pay $8.00 per day.
Write a program that calculates and prints the parking charges. The inputs to your program are the date and time when a car enters the parking garage, and the date and time when the same car leaves the parking garage. Both inputs are in the format of YY/MM/DD hh:mm
Here's the code I've written so far:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
#include <sstream>
using namespace std;
stringstream ss;
string enter_date;
string enter_time;
string exit_date;
string exit_time;
int calculatecharge;
int num;
int i;
int year;
int month;
int ddmmyyChar;
int dayStr;
string line;
int x;
void atk()
{
getline (cin,line); // This is the line entered by the user
stringstream ss1(line); // Use stringstream to interpret that line
ss >> enter_date >> enter_time;
stringstream ss2(enter_date); // Use stringstream to interpret date
string year, month, day;
getline (ss2, year, '/');
}
int main()
{
cout << "Please enter the date and time the car is entering "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
cout << "Please enter the date and time the car is exiting "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
if (hr - hr < 3)
cout<<"Parking fee due: $2.00" << endl;
Write a program that calculates and prints the parking charges.
This is the goal of our program. Basically, this is the output.
The inputs to your program are the date and time when a car enters the
parking garage, and the date and time when the same car leaves the
parking garage. Both inputs are in the format of YY/MM/DD hh:mm
So, we want some way of translating the date format entered as a string into a time difference. You could store the time in an int, which represents the amount of minutes elapsed during the parking period (I choose minutes since this is the smallest time period inputted). The challenge here is the parsing of the string into this integer.
You could write a function like this:
int parseDate( std::string dateStr )
{
// Format: YY/MM/DD hh:mm
int year = atoi( dateStr.substr( 0, 2 ).c_str() );
int month = atoi( dateStr.substr( 3, 2 ).c_str() );
int day = atoi( dateStr.substr( 6, 2 ).c_str() );
int hour = atoi( dateStr.substr( 9, 2 ).c_str() );
int min = atoi( dateStr.substr( 12, 2 ).c_str() );
// Now calculate no. of mins and return this
int totalMins = 0;
totalMins += ( year * 365 * 24 * 60 ); // Warning: may not be accurate enough
totalMins += ( month * 30 * 24 * 60 ); // in terms of leap years and the fact
totalMins += ( day * 24 * 60 ); // that some months have 31 days
totalMins += ( hour * 60 );
totalMins += ( min );
return totalMins;
}
Careful! My function here is just an illustration, and does not take into account subtleties like leap years and varying month length. You will probably need to improve on it. The important thing is to recognise that it attempts to take a string and return the number of minutes that have elapsed since year '00. This means we simply have to subtract two integers from the two date strings to find the elapsed time:
int startTime = parseDate( startDateString );
int endTime = parseDate( endDateString );
int elapsedTime = endTime - startTime; // elapsedTime is no. of minutes parked
This is probably the hardest part of the problem, once you have this worked out, the rest should be more straightforward. I will give you a few more tips:
A parking garage charges a $2.00 minimum fee to park for up to three
hours.
Basically just a flat rate: No matter what, the output variable that describes the cost should be equal to at least 2.00.
The garage charges an additional $0.50 per hour for each hour
or part thereof in excess of three hours.
Work out the amount of hours elapsed past three hours - subtract 180 from elapsedTime. If this is greater than 0, then divide it by 60 and store the result in a float (since it is not necessarily an integer result), called, say, excessHours. Use excessHours = floor( excessHours ) + 1; to round this number up. Now multiply this by 0.5; this is the extra cost. (Try to understand why this works mathematically).
The maximum charge for any
given 24-hour period is $10.00. People who park their cars for longer
than 24 hours will pay $8.00 per day.
I will leave this up to you to work out, since this is homework after all. Hopefully I have provided enough here for you to get the gist of what needs to be done. There are many possible approaches to this problem too, this is just one, and may or may not be "the best".
First of all as both the string for the date and the string for the time are continuous(contain no spaces), you do not need to use stringstream to parse the line. You can read the date and time just like this:
cin >> enter_date >> enter_time;
cin >> exit_date >> exit_time;
Now what you need is to convert these strings to actual dates and times. As the format of both is fixed you can write something like this:
void parse_date(const string& date_string, int& y, int& m, int& d) {
y = (date_string[0] - '0')*10 + date_string[1] - '0'; // YY/../..
m = (date_string[3] - '0')*10 + date_string[4] - '0'; // ../mm/..
d = (date_string[6] - '0')*10 + date_string[7] - '0'; // ../../dd
}
Of course this code is somewhat ugly and can be written in better way but I believe this way it is easier to understand. Having this function it should be obvious how to write this one:
void parse_time(const string& time_string, int& h, int &m);
Now that you have the date and time parsed, you need to implement a method that subtracts two dates. IN fact what you care about is the number of hours that elapsed from the enter date time to the exit date time rounded up. What I suggest here is that you convert the dates to number of days from some initial moment(say 00/01/01) and then subtract the two values. Then convert both times to number of minutes since 00:00 and again subtract them. This is not language specific so I believe these tips should be enough. Again using some built-in libraries this can be done easier but I don't think this is the idea of your assignment.
After you have the number of hours rounded up all you need to do is actually to implement the rules in the statement. This will only take a few ifs and is in fact quite easy.
Hope this helps. I am purposefully not giving more detailed explanations so that there is something left for you to think about. After all this is homework and is meant to make you think how to do it.
You don't need to perform separate input reading and parsing operations. You could pass the necessary variables by reference and read the input directly into the variables using stringstream. I would use a structure to store the date and time and overload operator- with an algorithm for subtracting two date/time values. Here's how I would do it:
#include <iostream>
#include <sstream>
using namespace std;
struct DateTime {
// Variables for each part of the date and time
int year, month, day, hour, minute;
// Naive date and time subtraction algorithm
int operator-(const DateTime& rval) const {
// Total minutes for left side of operator
int lvalMinutes = 525600 * year
+ 43200 * month
+ 1440 * day
+ 60 * hour
+ minute;
// Total minutes for right side of operator
int rvalMinutes = 525600 * rval.year
+ 43200 * rval.month
+ 1440 * rval.day
+ 60 * rval.hour
+ rval.minute;
// Subtract the total minutes to determine the difference between
// the two DateTime's and return the result.
return lvalMinutes - rvalMinutes;
}
};
bool inputDateTime(DateTime& dt) {
// A string used to store user input.
string line;
// A dummy variable for handling separator characters like "/" and ":".
char dummy;
// Read the user's input.
getline(cin, line);
stringstream lineStream(line);
// Parse the input and store each value into the correct variables.
lineStream >> dt.year >> dummy >> dt.month >> dummy >> dt.day >> dummy
>> dt.hour >> dummy >> dt.minute;
// If input was invalid, print an error and return false to signal failure
// to the caller. Otherwise, return true to indicate success.
if(!lineStream) {
cerr << "You entered an invalid date/time value." << endl;
return false;
} else
return true;
}
From here, in the main() function, declare two DateTime structures, one for the entry time and one for the exit time. Then read in both DateTime's, subtract the entry time from the exit time, and use the result to generate the correct output.