How many coins to give for change [closed] - c++

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.

Related

Cant display the numbers lost over 100

So in my little game, there is a happiness mechanic, I want it to be capped at 100, and show the player how much happiness they lost due to the overflow, but it keeps showing 100. (I created the integer happiness at the very start), its in a switch statement, all other parts of the switch work well.
case 5:
if (happiness <= 100) {
happiness = happiness + 20;
cout<< "The festival goes well";
if (happiness > 100) {
int lost_happiness = happiness - (happiness%100);
happiness = happiness - (happiness%100);
cout << ", however, happiness has reached the cap of 100. The amount lost is " << lost_happiness;
}
}
break;
Any ideas why?
From what I understand case 5 is always showing 100 and it should . Just think let initial happiness be 95 , you add 20 it becomes 115 .then you are subtracting 115%100 I.e. 15 from it , so the answer will become 100 in every case .
You are using the same formula to calculate both the lost_happiness and new happiness values:
int lost_happiness = happiness - (happiness%100); // Notice the similarity
happiness = happiness - (happiness%100); // in the two RHS codes?
This is incorrect, and the former should just be happiness % 100.
if (happiness <= 100) {
happiness += 20;
cout<< "The festival goes well";
if (happiness > 100) {
int lost_happiness = happiness % 100; // DON'T subtract this from total
happiness -= lost_happiness; // No need to recalculate the "%"
cout << ", however, happiness has reached the cap of 100. The amount lost is " << lost_happiness;
}
}
Note that I have also used some techniques to make your code rather more succinct; please feel free to ask for further details and/or clarification.

if statement inside of for loop not being executed

Writing a program to solve problem four of project euler: Find the largest palindrome made from the product of two 2-digit numbers. Heres my reprex:
#include <iostream>
int reverseNumber(int testNum)
{
int reversedNum, remainder = 0;
int temp = testNum;
while(temp != 0)
{
remainder = temp % 10;
reversedNum = reversedNum * 10 + remainder;
temp /= 10;
}
return reversedNum;
}
int main()
{
const int MIN = 100;
int numOne = 99;
int product = 0;
for(int numTwo = 10; numTwo < 100; numTwo++)
{
product = numOne * numTwo;
if (reverseNumber(product) == product)
{
int solution = product;
std::cout << solution << '\n';
return 0;
}
}
return 0;
}
My main thought process behind this is that the for loop will go through every number from 10 to 99 and multiply it by 99. My intended outcome is for it to print 9009 which is the largest palindrome with 2 factors of 2 digits. So what I think should happen here is the for loop will go from 10 to 99, and each loop it should go through the parameters of the if statement which reverses the number and sees if it equals itself.
I've made sure it wasn't a compiler issue, as this is recurring between different compilers. The reverseNumber() function returns the proper number every time I've tested it, so that shouldn't be the problem, however this problem only occurs when the function is involved in the logical comparison. By this I mean if that even I set it equal to a variable and put the variable in the if parameters, the issue still occurs. I'm pretty much stumped. I just hope it's not some silly mistake as I've been on this for a couple days now.
int reversedNum, remainder = 0;
You should be aware that this gives you (in an automatic variable context) a zero remainder but an arbitrary reversedNum. This is actually one of the reasons some development shops have the "one variable per declaration" rule.
In other words, it should probably be:
int reversedNum = 0, remainder;
or even:
int reversedNum = 0;
int remainder;
One other thing that often helps out is to limit the scope of variable to as small an area as possible, only bringing them into existence when needed. An example of that would be:
int reverseNumber(int testNum) {
int reversedNum = 0;
while (testNum != 0) {
int remainder = testNum % 10;
reversedNum = reversedNum * 10 + remainder;
testNum /= 10;
}
return reversedNum;
}
In fact, I'd probably go further and eliminate remainder altogether since you only use it once:
reversedNum = reversedNum * 10 + testNum % 10;
You'll notice I've gotten rid of temp there as well. There's little to gain by putting testNum into a temporary variable since it's already a copy of the original (as it was passed in by value).
And one other note, more to do with the problem rather than the code. You seem to be assuming that there is a palindrome formed that is a multiple of 99. That may be the case but a cautious programmer wouldn't rely on it - if you're allowed to assume things like that, you could just replace your entire program with:
print 9009
Hence you should probably check all possibilities.
You also get the first one you find which is not necessarily the highest one (for example, let's assume that 99 * 17 and 99 * 29 are both palindromic - you don't want the first one.
And, since you're checking all possibilities, you probably don't want to stop at the first one, even if the nested loops are decrementing instead of incrementing. That's because, if 99 * 3 and 97 * 97 are both palindromic, you want the highest, not the first.
So a better approach may be to start high and do an exhaustive search, while also ensuring you ignore the palindrome check of candidates that are smaller that your current maximum, something like (pseudo-code)
# Current highest palindrome.
high = -1
# Check in reverse order, to quickly get a relatively high one.
for num1 in 99 .. 0 inclusive:
# Only need to check num2 values <= num1: if there was a
# better palindrome at (num2 * num1), we would have
# already found in with (num1 * num2).
for num2 in num1 .. 0 inclusive:
mult = num1 * num2
# Don't waste time doing palindrome check if it's
# not greater than current maximum - we can't use
# it then anyway. Also, if we find one, it's the
# highest possible for THIS num1 value (since num2
# is decreasing), so we can exit the num2 loop
# right away.
if mult > high:
if mult == reversed(mult):
high = mult
break
if high >= 0:
print "Solution is ", high
else:
print "No solution"
In addition to properly initializing your variables, if you want the largest palindrome, you should switch the direction of your for loop -- like:
for(int numTwo = 100; numTwo > 10; numTwo--) {
...
}
or else you are just printing the first palindrome within your specified range

Need help beginning C++ program

I'm just starting to learn c++ i just want to ask how can I loop this? Please, don't give me direct answer give me a clue or just a "work frame" how to solve this problem. I want to solve it on my own.
So I'm kinda getting difficulties in looping decimals only i can loop solid numbers but i have some troubles looping decimal figures.
P.S Im reviewing for an exam 4 hours from now but this might come up, i having difficulties in this types of question.
This is the question:
Shipping Cost Calculator
A mail order company charges $3.00 for handling, free shipping for orders 10 pounds or less, plus $0.25 for each pound over 10. Write a program that repeatedly asks the user for the weight of an order, then writes out the shipping charge. The program stops when a weight of zero or less is entered.
Weight of Order:
5
Shipping Cost: $3.00
Weight of Order
20
Shipping Cost: $5.50
Weight of Order
0
bye
I keep on practicing to this but i seem to find error on a formula
how can I loop 3.25 to 4.50 to 5.75 to 6.00 and so on?
main() {
float a, b, x;
printf("Enter Weight: ");
scanf("%f", &a);
if (a <= 10)
{
printf("Your balance is 3.00");
}
else if (a > 10)
{
for (x =.25; x <= a; x++)
{
printf("Your balance is %.2f \n", a);
a += + .25;
}
}
else if (a == 0)
{
printf("Bye");
}
getche();
}
for ( double x = 3.25; x <= so_on; x += 1.25 ) { /*...*/ }
or
for ( float x = 3.25f; x <= so_on; x += 1.25f ) { /*...*/ }

How to improve my code about the growing of a bacterial colony (C++) [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I'm coding a program to calculate the growth of a bacterial colony until certain point.
Given a "X", that will represent the initial number of bacteria. And given a "Y", that will represent the number limit desired of bacteria in the bacterial colony. Return the number of days and hours that the bacterial colony needs for reaching the limit.
The bacterial colony doubles each hour.
Example.1:
Input: 1, 8
Output: 0, 3
Example.2:
Input: 1000 , 1024000
Output:0, 10
Example.3:
Input: 123, 3453546624536
Output: 1, 10
If the hour calculated returns a fractional number, it must be rounded down.
So far I have written this code:
#include <iostream>
using namespace std;
int main(){
long int binitial, blimit, day, counter=0;
float hour;
cin >> binitial;
cin >> blimit;
while(binitial <= blimit){
binitial = binitial * 2;
counter++;
}
day = counter / 24;
cout << day << " ";
hour = (counter % 24) - 0.5;
cout << (int)hour;
return 0;
}
You can remove the loop by observing that the number of hours is Log2(Y/X). To calculate Log2(A) using the standard functions, calculate log(A)/log(2).
You may need to address precision issues when going from doubles to ints, because the calculations will be approximate. The final expression for the hours may look like this:
int hours = (log(Y/X) / log(2)) + 1E-8; // Add a small delta
Going from hours to days/hours is very simple, too:
cout << hours/24 << " " << hours % 24 << endl;
You can use a long int for hour if you do the following:
hour = counter - (day*24); // The total number of hours minus the number of hours that are in each day.
I don't have a compiler in front of me but you can probably also do something like this:
hour = counter % 24; // this will return the remainder when counter is divided by 24.
If blimit is always a multiple of binitial, the solution is simple:
counter%24 will be always an integer, so you don't have to round it.
In case of day days and hour hours, you only have to do is:
hour = counter%24
A note on the method of calculation: you don't need to iterate if you're only doubling each time. You're just looking for a value of n such that 2n gives the right result.
So, note that ngenerations = log2 blimit - log2 binitial
Once you have the number of generations (as a floating-point number) you can just truncate that to an integer number of hours.

am i on the right track? Cashier Program 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.