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);
Related
(this function is part of a larger program but operates independently of other functions.)
Ok I have a function jacket and given 3 inputs it produces the correct output only 75% of the time.
I do not know the inputs but I know the output is wrong.
I do not know what is wrong and have no idea how to fix it.
I assume it is the same 12 values entered each time the function is submitted to myProgrammingLab.
So it may be a problem with a specific input.
Thanks.
The Description:
Jacket size (chest in inches) = height times weight divided by 288 and then adjusted by adding 1/8 of an inch for each 10 years over age 30. (note that the adjustment only takes place after a full 10 years. So, there is no adjustment for ages 30 through 39, but 1/8 of an inch is added for age 40.)
edit: changing tmp to float still produced the error.
float jacket(float weight, float height, int age) {
double result = (height * weight) / 288;
/*now for every 10 years past 30 add (1/8) to the result*/
if((age - 30) > 0){
int temp = (age - 30) / 10;
result = result + (temp * .125);
}
return result;
}
This is the same function written differently with the same problem.
float jacket(double jWeight, double jHeight, int jAge)
{
double jSize = ((jWeight*jHeight)/288.0);
int i = jAge/10 - 3;
if((jAge/10)>3)
jSize += 0.125*i;
return jSize;
}
This is a third function with the same problem
float jacket(double weight, double height, int age)
// calculates the jacket size, adjusting for age in increments
// of ten years, if customer is over 30 years of age.
{
int age_factor;
double j_size;
j_size = (height*weight)/288.0;
if (age >=30)
{
age_factor = (age-30)/10; //note possible truncation.
j_size += age_factor/8.0;
}
return j_size;
}
The first time the function is called it produces an incorrect return value. the remain 3 times it is called the return value is correct.
Observe:
Expected Output:
jacket·size·=·24.17↵
jacket·size·=·40.00↵
jacket·size·=·46.04↵
jacket·size·=·35.42↵
Actual Output:
jacket·size·=·24.29↵
jacket·size·=·40.00↵
jacket·size·=·46.04↵
jacket·size·=·35.42↵
*All three functions given the same input produce the same output
int temp = (age - 30) / 10;
By making temp an int, you will get incorrect results, because of truncation. Try using a float instead.
I guess one could say that 31 isn't necessarily 1 year over 30. Try int temp = (age - 31)/10;. Personally I think that's wrong, as does everyone else here, but someone could argue that the moment one turns 31 one is only a few seconds over 30. It's worth a try, anyway.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am new to c++. The problem consists in minimizing the number of coins required to give the exact change I have 25 10 5 and 1 cent coins.
For example if a customer is owed $3.20 the number of coins to give would be 14 (12 of 25 and 2 of 10).
My problem:
A number like 4.20 says you need 22 coins instead of 18. I know the problem is generated when it multiplies change by 100. I get 419 instead of 420.
Here is my code.
int coins = change * 100;
//How many 25 cent coins you need
if (coins >= 25)
{
quarter = coins / 25;
coins = coins % 25;
}
//How many 10 cent coins you need
if (coins >= 10)
{
dimes = coins / 10;
coins = coins % 10;
}
//How many 5 cent coins you need
if (coins >= 5)
{
nickels = coins / 5;
coins = coins % 5;
}
//How many 1 cent coins you need
if (coins >= 1)
{
pennies = coins / 1;
coins = coins % 1;
}
NumCoins = quarter + dimes + nickels + pennies;
printf("%d \n", NumCoins);
Thanks for your help.
#include<iostream>
using namespace std;
int main()
{
int amount = 420;
int coins[] = { 25, 10, 5, 1 };
int ncoins = 0;
for( int i=0 ; i<sizeof(coins)/sizeof(int) ; ++i )
{
ncoins += amount / coins[i];
amount %= coins[i];
}
cout << "You need " << ncoins << " coin(s)." << endl;
}
You need 18 coin(s).
It is easy to track which specific coins are needed in the for loop. I assume the reader can adjust the code as needed to suit their purposes.
From my understanding of the problem my suggestion on how to do this is essentially having two variables. change (This is the change you have in cents.) as well as coins (This is the total number of coins you need to make change.)
Then once you have the change, you keep subtracting the quarters (that is 25), from the change variable until it is less than 25, then you move onto dimes, nickels and finally pennies. At the same time you decrement the change variable, you increment the coins in order to keep track of the minimum number of coins you need. This should be much cleaner and simpler than keeping track of all these other variables.
Some pseudocode could look like this:
declare variables
do loop of change > 25
change = change - 25
coins = coins + 1
do loop of change > 10
...
(keep doing this for dimes, nickels and pennies)
...
display number of coins needed.
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.
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.
Hi to all thank all in advance to those who tried to answer or answer and part of this question.
Calculate the sum of the digits of the year.
Calculate the absolute value of the difference between the year and the ’reverse’ of the year.
Calculate the number of even factors of the day.
Calculate the greatest common divisor of the day, month and year.
Calculate the number of steps required to solve the Collatz problem for
the month
These are my tasks that I need to fulfill, as Engineering student this how far I went in this. In the following codes I expect something like this
19
90
0
1
0
T M B B
The answer that I get is
Please enter your birthdate (dd mm yyyy): 12 11 1981
19
8468304
Press any key to continue . . .
8468304
How to get it right I know that my equation is right or(formula, method). However this is what I know.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
cout << "Please enter your birthdate (dd mm yyyy): ";
int day, month, year, count,rev;
int sum = 0;
cin >> day>> month >>year;
while (year!=0)
{
int count = year%10;
sum +=count;
year /= 10;
}
while(year>0)
{
rev = year%10;
year=year/10;
}
cout<<sum<<endl;
cout << rev;
system ("pause");
return 0;
}//end main
Please help!
After your first loop, while (year != 0), you don't reset the value of year, so it remains at zero and the second loop doesn't execute at all.
You need to save the value of year and use it when you start the second loop.
Just a note on organisation: I'd suggest to write a subroutine/function for every task, like
int digit_sum(int year) {
/* ... */
return sum;
}
int reverse_difference(int year) {
/* ... */
return diff;
}
and so on. This way you'll also prevent errors like modifying the year variable during the first calculation without saving the original value (which you did, as David Winant already pointed out).