C++ cashier code - c++

The question:
Giving change. Implement a program that directs a cashier how to give
change. The program has two inputs: the amount due and the amount
received from the customer. Display the dollars, quarters, dimes,
nickels, and pennies that the customer should receive in return.
What i have so far:
#include <iostream>
using namespace std;
int main()
{
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change % 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) % 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) % 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) % 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) % 1 << endl;
system("pause");
return 0;
}
I realize there are some other one of these answered but they may be to advanced to use in my code, what am i doing wrong?

What you want to do is the same as a cashier would do.
First ensure the change is represented as whole pennies.
Then provide enough dollars until the change remaining is less than a dollar. Then move on to quarters, then dimes, nickels and pennies.
So for the dollar case, pseudo-code would be:
dollars = change / 100 # get integral number of dollars
change = change % 100 # and reduce change-left-to-go accordingly
print dollars, " dollars"
It should then be a simple matter to apply that logic to the other coin types in order of reducing value.

There are several problems. The first is that you ask the user to input values, but don't specify what they are. If the user enters a number that's not in pennies, you're not going to get the value you expect. I expect this input should be in dollars. So, first, change change into:
change = int((amount_recieved - amount_due) * 100.0)
Next:
cout << "dollars: " << change % 100 << end;
Will return the remainder of dividing change by 100, which is not what you want. You simply want to divide dollars by 100. You also want to likely modify change to stop you having to repeat this math.
dollars = change / 100;
cout << "dollars: " << dollars << endl;
change -= dollars*100;
From there, the rest of the code should work as expected minus the % 100 parts. As others have mentioned in the comments to the question, your problem is arising from not thinking the math through first, not from doing anything inherently wrong with C++. This would have produced the wrong result in any language, including writing it down as math on a blackboard.

As others have mentioned, you are not doing the step required to get this working, and that is repeated subtraction. Yes, you subtracted the price from the amount given, and determined the dollars to give, but you failed to subtract out those dollars, giving you a new total to determine how many quarters.
Something like this (assuming you're working in pennies):
change_left = customer_payment - original_cost;
//...
number of dollars = change_left / 100;
change_left = change_left - (100 * number of dollars); <-- where is this?
Now how do you determine the number of quarters? You have a "running total" called change_left that is being reduced by the change you currently have given the customer. You repeat similar steps to get the number of quarters, then number of dimes, nickels, etc., i.e. divide by 25, then subtract out the number of quarters giving a new "change_left". Then repeat for 10 to get the dimes, 5 to get the number of nickels, etc.
So again, the problem isn't C++ -- the issue is that you are not thinking this out as a discrete series of steps that lead to a final goal.

#include <iostream>
using namespace std;
int main() {
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change / 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) / 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) / 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) / 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) / 1 << endl;
return 0;
}

Related

What does this function expect to return?

Program specifies the following:
Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line.
The coin types are dollars, quarters, dimes, nickels, and pennies.
Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies.
Your program must define and call the following function.
void ExactChange(int userTotal, vector& coinVals)
Positions 0-4 of coinVals should contain the number of dollars, quarters, dimes, nickels, and pennies, respectively.
My code is below:
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
/*
1) Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line.
2) The coin types are dollars, quarters, dimes, nickels, and pennies.
3) Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies.
4) Your program must define and call the following function.
void ExactChange(int userTotal, vector<int>& coinVals)
5) Positions 0-4 of coinVals should contain the number of dollars, quarters, dimes, nickels, and pennies, respectively.
*/
void ExactChange(int userTotal, vector<int>& coinVals);
const int PENNIES_IN_DOLLAR = 100, PENNIES_IN_QUARTER = 25, PENNIES_IN_DIME = 10, PENNIES_IN_NICKEL = 5;
int main() {
int userTotal, changeRemaining;
cin >> userTotal;
changeRemaining = userTotal;
int dollars = changeRemaining / PENNIES_IN_DOLLAR;
changeRemaining = changeRemaining % PENNIES_IN_DOLLAR;
int quarters = changeRemaining / PENNIES_IN_QUARTER;
changeRemaining = changeRemaining % PENNIES_IN_QUARTER;
int dimes = changeRemaining / PENNIES_IN_DIME;
changeRemaining = changeRemaining % PENNIES_IN_DIME;
int nickels = changeRemaining / PENNIES_IN_NICKEL;
changeRemaining = changeRemaining % PENNIES_IN_NICKEL;
int pennies = changeRemaining;
vector<int> changeAmount;
vector<int> coinVals{dollars, quarters, dimes, nickels, pennies};
changeAmount = coinVals;
ExactChange(userTotal, changeAmount);
return 0;
}
void ExactChange(int userTotal, vector<int>& coinVals) {
if (userTotal == 0) {
cout << "no change" << endl;
}
if(coinVals.at(0) > 0) {
cout << coinVals.at(0);
if(coinVals.at(0) > 1) {
cout << " dollars" << endl;
}else {
cout << " dollar" << endl;
}
}
if(coinVals.at(1) > 0) {
cout << coinVals.at(1);
if(coinVals.at(1) > 1) {
cout << " quarters" << endl;
} else {
cout << " quarter" << endl;
}
}
if(coinVals.at(2) > 0) {
cout << coinVals.at(2);
if(coinVals.at(2) > 1) {
cout << " dimes" << endl;
}else {
cout << " dime" << endl;
}
}
if(coinVals.at(3) > 0) {
cout << coinVals.at(3);
if(coinVals.at(3) > 1) {
cout << " nickels" << endl;
}else {
cout << " nickel" << endl;
}
}
if(coinVals.at(4) > 0) {
cout << coinVals.at(4);
if(coinVals.at(4) > 1) {
cout << " pennies" << endl;
}else {
cout << " penny" << endl;
}
}
}
However, zybooks, the site where our college course does our labs gives me these messages indicating some problem with my code:
My question is, what do those "messages" mean? Any how could I fix the issues? It seems to me they are saying the function is outputting something incorrectly given a certain input, however, they also don't give me a correct output to compare to.
Your code is taking user input, converting it manually directly in main() before calling ExactChange(), and then passing the result of that conversion to ExactChange() for it to display as-is.
The way I read the instructions, and the way the screenshot shows the tests being performed, it is more likely that ExactChange() is expected to take user input and convert it onto a vector of coin amounts as output.
That would be consistent with the fact that ExactChange() takes a vector by non-const reference, which means it can freely modify the contents of the vector. If ExactChange() were meant for text output, it would make more sense for it to take the vector by const reference instead, so that it can't modify the vector, only view it.
If so, then it makes sense that your program would pass tests that give it user-defined input and look for specific text results, but your program would fail tests that execute ExactChange() directly with specific inputs and look for specific vector outputs. That is the whole point of Unit Tests - to test functions directly for expected behaviors, not test whole programs.
Your code likely needs to look more like the following instead:
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
/*
1) Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line.
2) The coin types are dollars, quarters, dimes, nickels, and pennies.
3) Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies.
4) Your program must define and call the following function.
void ExactChange(int userTotal, vector<int>& coinVals)
5) Positions 0-4 of coinVals should contain the number of dollars, quarters, dimes, nickels, and pennies, respectively.
*/
void ExactChange(int userTotal, vector<int>& coinVals);
const int PENNIES_IN_DOLLAR = 100, PENNIES_IN_QUARTER = 25, PENNIES_IN_DIME = 10, PENNIES_IN_NICKEL = 5;
int main() {
int userTotal;
cin >> userTotal;
if (userTotal == 0) {
cout << "no change" << endl;
}
else {
vector<int> coinVals;
ExactChange(userTotal, coinVals);
if (coinVals[0] > 0) {
cout << coinVals[0];
if (coinVals[0] > 1) {
cout << " dollars" << endl;
} else {
cout << " dollar" << endl;
}
}
if (coinVals[1] > 0) {
cout << coinVals[1];
if (coinVals[1] > 1) {
cout << " quarters" << endl;
} else {
cout << " quarter" << endl;
}
}
if (coinVals.at(2) > 0) {
cout << coinVals[2];
if (coinVals[2] > 1) {
cout << " dimes" << endl;
}else {
cout << " dime" << endl;
}
}
if (coinVals[3] > 0) {
cout << coinVals[3];
if (coinVals[3] > 1) {
cout << " nickels" << endl;
}else {
cout << " nickel" << endl;
}
}
if (coinVals[4] > 0) {
cout << coinVals[4];
if (coinVals[4] > 1) {
cout << " pennies" << endl;
}else {
cout << " penny" << endl;
}
}
}
return 0;
}
void ExactChange(int userTotal, vector<int>& coinVals) {
int dollars = userTotal / PENNIES_IN_DOLLAR;
userTotal %= PENNIES_IN_DOLLAR;
int quarters = userTotal / PENNIES_IN_QUARTER;
userTotal %= PENNIES_IN_QUARTER;
int dimes = userTotal / PENNIES_IN_DIME;
userTotal %= PENNIES_IN_DIME;
int nickels = userTotal / PENNIES_IN_NICKEL;
userTotal %= PENNIES_IN_NICKEL;
int pennies = userTotal;
coinVals.resize(5);
coinVals[0] = dollars;
coinVals[1] = quarters;
coinVals[2] = dimes;
coinVals[3] = nickels;
coinVals[4] = pennies;
}
I agree with Remy. An easier way of saying it would be that Zybooks sets the size for the vector as you open the section:
vector<int> changeAmount(5);
To pass the two problems, instead of clearing out the (5) or push_back'ing the amounts (which is 100% what I originally did), you just need to point the coin amount to the already created vector index directly.
Your code did this:
vector<int> coinVals{dollars, quarters, dimes, nickels, pennies};
changeAmount = coinVals;
When all you needed to do for each amount was:
coinVals.at(3) = dollars;
Because the vector is pass by reference (that '&' right before the vector name), your updates to the vector will be carried back through to your main function.
Thanks for posting! This thread helped me solve this one as well!

The rand() function in C++ is giving a number outside the range

So I'm trying to write a story about Jordan paying bills and stuff. I used a rand function to find a random number for his salary 3.5k - 4.5 and bills 700 -1.5k. I believe I got the formula right but usually, it generates a number outside that area. Below is the code and result.
{
srand(time(NULL));
cout << fixed;
cout << setprecision(2);
float money = 9000;
int minbill = 700;
int maxbill = 1500;
int minsal = 3500;
int maxsal = 4500;
float rent = 3000;
cout << "[Jordan's Balance: Gp" << money << "]\n\n";
cout << "Jordan's rent costs Gp" << rent <<".\n";
float bill = (rand()%maxbill-minbill+1)+minbill;
cout << "Jordan's bills costs Gp" << bill << ".\n";
float totalb = rent + bill;
cout << "Jordan needs to pay a total of Gp" << totalb << "\n\n";
float sal = (rand()%maxsal-minsal+1)+minsal;
cout << "Jordan received a salary of Gp" << sal << "!!\n";
money = money + sal;
cout << "[Jordan's Balance: Gp" << money << "]\n\n";
}
I expect Jordan's bills to be around 700-1.5k and his salary 3.5k-4.5k but it gives me a number below that.
Jordan's rent costs Gp3000.00.
Jordan's bills costs Gp133.00.
Jordan needs to pay a total of Gp3133.00
Jordan received a salary of Gp1906.00!!
[Jordan's Balance: Gp10906.00]
(rand()%maxbill-minbill+1) is wrong.
It's possible that rand()%maxbill will be less than minbill. You need to use rand() % (maxbill - minbill + 1).
float bill = rand() % (maxbill-minbill+1) + minbill;
Similarly, use
float sal = rand() % (maxsal-minsal+1) + minsal;

C++ coins conversion hw [duplicate]

This question already has answers here:
c++ integer division
(3 answers)
Closed 3 years ago.
The last part of my code doesn't seem to run
#include <iostream>
#include <cmath>
int main() {
int dollars;
int cents;
std::cout << "Please enter your amount in the format of dollars and cents separated by a space: ";
std::cin >> dollars >> cents;
double quarters = dollars/0.25;
int whole_quarters = (int) quarters;
double dimes = cents/10;
int whole_dimes = (int) dimes;
double nickels = (dimes - whole_dimes)/0.5;
int whole_nickels = (int) nickels;
int pennies = std::fmod((dimes - whole_dimes),0.5);
std::cout << dollars << " dollars and " << cents << " cents are:\n";
std::cout << whole_quarters << " quarter " << whole_dimes << " dimes " << whole_nickels << " nickels " << pennies << " pennies ";
return 0;
}
I typed in 2 58 but the output was 8 quarters 5 dimes 0 nickels 0 pennies
It should be 1 nickels and 3 pennies
Can someone tell me what am i missing?
A better answer would be 10 quarters, 1 nickle, 3 pennies. Be that as it may.
I wouldn't have used this particular algorithm, although scanning it isn't telling me the obvious problem. I would debug by dumping out dimes (the double) and verify it's what you think it is, and then nickles (the double) and make sure that value makes sense, too.
I would do something like this:
int dimes = cents / 10;
int nickles = (cents % 10) / 5;
int pennies = (cents % 5);
If cents is 58, then dimes = 5, cents % 10 is 8, divided by 5 is 1, and cents % 5 is 3.
But it's worthwhile, if you're serious about programming, to put a lot of cout statements into your code and make sure values are becoming what you think they are.
Also, this will be faster if instead of asking for input, you comment out that code and hardcode your test data. Once you're getting proper test results that way, then switch back to asking for input.

C++ program on how much a person would earn over time if salary is one penny per day (Not an IT student)

I have a project to write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
This is my code so far and I can't seem to get it to work properly (not an
IT student)
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip.h>
int main()
{
int days;
double pennies = 0.01;
double total = 0.0;
double fixed;
double showpoint;
cout << "For how many days will the pay double?";
cin >> days;
cout << endl << "Day Total Pay\n";
cout << "------------------------\n";
for (int count = 1; count <= days; count++)
{
cout << count << "\t\t$\t" << (pow(2, pennies)) << endl;
}
cout << setprecision(2) << fixed << showpoint;
cout << "--------------------------------\n";
cout << "Total $\t" << total << endl;
getch();
return 0;
}
I've tried to explain the changes I have made, but if you need to know more please ask
// Headers for standard library features don't have .h on the end (normally)
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip>
int main()
{
int days = 0;
// double pennies = 0.01; Not needed.
double total = 0.0;
// If you don't initialise variables it will cause a crash or undefined behaviour.
// double fixed;
// double showpoint;
while (days < 1) // This prevents negative or 0 day contracts.
{
// You need to use the full name to cout or that abomination of a command using namespace std
std::cout << "For how many days will the pay double?";
std::cin >> days;
}
std::cout << std::endl << "Day Total Pay\n";
std::cout << "------------------------\n";
// looping from 0 while less than days is more "normal".
for (int count = 0; count < days; count++)
{
double payForTheDay = (pow(2, count));
std::cout << count << "\t\t$\t" << payForTheDay << std::endl;
total += payForTheDay; // You need to increment the total.
}
// Not sure what this is about
// std::cout << std::setprecision(2) << fixed << showpoint;
std::cout << "--------------------------------\n";
std::cout << "Total $\t" << total << std::endl;
getch();
return 0;
}
Try to replace (pow(2, pennies)) with (pennies * pow(2, (count - 1)))...
Notes:
Shouldn't pennies actually be named dollars?
To calculate the total, just increase it by the daily salary for each day (e.g. inside the loop where you output each table row).
So look at the basic of the problem. It is basically a geometric progression.
In a geometric progression sum of n numbers is;
Sn=a1((1-r^n)/(1-r))
[a1=first element(in your case 1);r=2(in this case)]
Use the formula to get number of pennies for n days.
Now convert it into dollar value.
If you need full code comment here.
Quite late, but using bitwise shift is the best thing for 2^n in my opinion. It's fast and easy to use.
int days; // = amount of days for payment;
// Add input/output logic
if (days<1) {
// Do invalid input logic
}
// Use long long if days>31
for (int K=0; K<days; K++)
cout<<"Day "<<K<<": "<<(1<<K)<<"\n;
Here 1<<K is 2^K
Alternatively, you can use a variable to save the payment
and shift it by 1 each iteration.

How to perform mathematical operations?

I have been given the following assignment and am unsure how to implement it:
Calculate the fee for a taxi ride. The formula is as follows:
The first kilometer costs 50. Each extra 200m costs 5. If the distance
is more than 30km then each extra kilometer adds 10 to the fee. The
program has to input the total distance (in km) and calculate the
charge.
I wrote the following code but don't know what to do with "200m costs 5" part...
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
double totalfee, km, m;
cout << "distance" << endl;
cin >> km;
m = km * 1000;
if (km < 30)
{
totalfee = 50;
cout << "totalfee = " << totalfee << endl;
}
else if (km > 30)
{
totalfee = 60;
cout << "totalfee = " << totalfee << endl;
}
system("pause");
}
it is in c++
Firstly, the question contains some ambiguities - we know that the first km costs 50, and any 200m above the first km adds an additional 5. However, if the distance is greater than 30km, is the 10 per km fee additional on top of the 5, or does it replace the 5? Additionally, should partial amounts count e.g. is 5 charged if the total distance is 1100m? I'll assume that a partial amount does not count.
Secondly, you have some logic errors in your code. This block:
if (km < 30)
{
totalfee = 50;
cout << "totalfee = " << totalfee << endl;
}
Ignores the extra 5s that you should be charging above the first 1km.
The next block:
else if (km > 30)
{
totalfee = 60;
cout << "totalfee = " << totalfee << endl;
}
Contains the same logic error as the first, but also ignores the extra 10 to charge for each km, only charging this once (and charging it when it shouldn't at all, e.g. if the total km is 30.5).
You could try something like this:
//Assuming the two fees are both added separately from one another:
totalfee = 50; // Charge at least this much no matter what
// Pseudo-code:
if (km > 1)
{
// Subtract 1 from km
// Divide result by 0.2, discard any remainder
// Multiply result by 5, and add the total to totalfee
}
if (km > 30)
{
// Subtract 30 from km
// Divide result by 1, discard any remainder
// Multiply result by 10, and add the total to totalfee
}
cout << "totalfee = " << totalfee << endl;