I need help getting this program to properly print my outputs - c

#include <stdio.h> /*printf and scanf option*/
#include <math.h>
void change(double coin_change, int *quarters, int *dimes, int *nickels, int *pennies); /*function protype*/
int main(void)
{
int fifties = 0, twenties = 0, tens = 0, fives = 0, dollars = 0, quarters = 0, dimes = 0, nickels = 0, pennies = 0;
double amt_paid = 0, amt_due = 0, amt_change = 0, coin_change = 0; /*declared avriables*/
printf("Enter the amount paid> "); /*Prompt user to enter amount paid*/
scanf("%lf", &amt_paid);
printf("Enter the amount due> "); /*Prompt user to enter amount due*/
scanf("%lf", &amt_due);
amt_change = amt_paid - amt_due; /*Formula for amount of change to be given*/
dollars = (amt_change);
coin_change = (int)((amt_change - (amt_change)) * 100 + 0.5);
coin_change = coin_change * 100;
printf("\n%f\n", coin_change);
change(coin_change, &quarters, &dimes, &nickels, &pennies);
printf("Change is fifties: %d$, twenties: %d$, tens: %d$, fives: %d$, dollars: %d$, quarters: %d, dimes: %d, nickels: %d,\
pennies: %d", fifties, twenties, tens, fives, dollars, quarters, dimes, nickels, pennies);
return(0);
}
void change(double coin_change, int *quarters, int *dimes, int *nickels, int *pennies)
{
int q = 1, d = 1, n = 1, p = 1;
do {
if(coin_change >= 25){
*quarters = *quarters + q;
coin_change = coin_change - 25;
}
else if (coin_change >= 10) {
*dimes = *dimes + d;
coin_change = coin_change - 10;
}
else if (coin_change >= 5) {
*nickels = *nickels + n;
coin_change = coin_change - 5;
}
else if (coin_change >= 1) {
*pennies = *pennies + p;
coin_change = coin_change - 1;
}
} while (coin_change >= 1);
}
I'm sorry I wasn't very clear the first time. What I need is to create what is basically a cash register program. When given the amount due, and the amount paid from the user, i should receive output that tell me how many 50 dollar bills, 20s, 10s, 5s, 1s, quarters, dimes, nickels, and pennies I should be receiving as change. As I am new to programming, the code you see is what is to the best of my knowledge. I do need to improve or even completely change it. What I am really looking to do is pinpoint my mistakes, and fix them. I am hoping to have this code done soon. I feel that I am close, but only just missing it. Maybe I am wrong, but that is what I am coming to you guys for.

A couple of things:
you have many unused variables: fifties, twenties, tens, fives, dollars, etc.
The lines here:
coin_change = (int)((amt_change - (amt_change)) * 100 + 0.5);
coin_change = coin_change * 100;
Are wrong. They should be replaced with something like the following:
coin_change = (100 * amt_change).
Have you heard of the += / -= operators? They'd turn these lines:
*quarters = *quarters + q;
coin_change = coin_change - 25;
Into this:
*quarters += q;
coin_change -= 25;
After I fixed those things, your code worked fine.

I don't want to write the code for you because this smells like homework, but here's the algorithm:
read_from_keyboard(amount_due)
read_from_keyboard(amount_paid)
change = amount_paid - amount_due
for each denomination in (
fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pennies) {
while (change >= value of denomination) {
increment counter for denomination
subtract value of denomination from change
}
print counter + name of denomination // Ex: "4 twenties"
}
The "trick" is to realize that you can treat whole dollar values and coins in exactly the same way -- part of the art of programming is being able to find a generic solution that you can re-use, rather than handling each situation as a special case.
You may want to convert the change to an integer that represents the value in cents, so you can avoid the rounding errors that floating-point arithmetic creates.
Good luck!

Related

I came up with my own version of "Cash" problem from CS50x, can I optimize it? [duplicate]

This question already has answers here:
Cannot figure out how to properly increment a variable inside of a while loop, C
(2 answers)
Closed 2 years ago.
So basically, cash is a problem where you need to code a program that counts how many coins there is in a set sum.
For instance : for 0.41$, the minimum coins you can owe is 4 (1 quarter, 1 dime, 1 nickel, 1 penny).
The exercise will ask you just to code something that will answer : 4 for the entry "0.41"
I changed a bit the program so it answers for 4.2$ for example :
"16 quarter(s)
2 dime(s)
0 nickel(s)
0 penny(ies)" and was wondering if there is a way to optimize the code and make it better ?
Here is the code :
#include <cs50.h>
#include <math.h>
int main(void)
{
//Prompt user for an amount of change
float n;
do
{
n = get_float("How much change is owed for : (in $)\n");
//Verify if the float is positive
}
while (n < 0);
//Multiply 'n' by 100 to avoid float imprecisions
int cent = round(n * 100);
// Initialize the number of quarters (zero initially)
int quarters = 0;
while (cent >= 25)
{
quarters++;
cent = cent - 25;
}
// Initialize and calculate the number of dimes (zero initially)
int dimes = 0;
while (cent >= 10)
{
dimes++;
cent = cent - 10;
}
// Initialize and calculate the number of nickels (zero initially)
int nickels = 0;
while (cent >= 5)
{
nickels++;
cent = cent - 5;
}
// Initialize and calculate the number of pennies (zero initially)
int pennies = 0;
while (cent >= 1)
{
pennies++;
cent = cent - 1;
}
//Print the results
printf("%i quarter(s)\n", quarters);
printf("%i dime(s)\n", dimes);
printf("%i nickel(s)\n", nickels);
printf("%i penny(ies)\n", pennies);
}
As suggested by #MikeCAT, it'd be great to change it such that you use division and the modulo operator. This way, you'll avoid your while loop saving a few operations. Further, as #Weather Vane suggested, you can also have an array of multiple coin values and a singular loop. It'd also be great to print the coins depending on what all denominations there are. It would also be nice to determine the number of denominations (n_denomintations) at runtime. The code for the same would look like:
int cent = round(n * 100);
int denominations[n_denominations] = {25, 10, 5, 1}; // coins in descending order, alternatively ascending order and iterate in opposite
int n_denominations = sizeof(prices) / sizeof(prices[0]); // how many denominations of coins
int coins[n_denominations];
for (int i = 0; i < n_denomintations; i++) {
coins[i] = cent / 25; // implicitly typecasts to int, meaning that quarters will get whatever value cent / 25 is, rounded down
cent = cent % denominations[i]; // will give whatever amount remains after removing quarters
}
for (int i = 0; i < n_denominations; i++) {
printf("%i cent coins: %i\n", denomintations[i], coins[i]);
}

Cannot figure out how to properly increment a variable inside of a while loop, C

EDIT: After re-writing my code in my IDE, for the 8th time today, I have made rookie mistake of giving my inputs a false data type, that has been fixed but my outputs still are incorrect.
Details about my goal: When making change, odds are you want to minimize the number of coins you’re dispensing for each customer.
Well, suppose that a cashier owes a customer some change and in that cashier’s drawer are quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢). The problem to be solved is to decide which coins and how many of each to hand to the customer.
Expected Result:
Change owed: 0.41
4
Actual result:
Change owed: 0.41
3
#include <math.h>
#include <cs50.h>
#include <stdio.h>
int main (void)
{
float dollars;
int changeowed = 0;
do
{
dollars = get_float ("Change owed: ");
}
while (dollars < 0);
float cents = round(dollars * 100);
while (cents >= 25)
{
cents = cents - 25;
changeowed++;
}
while (cents > 10)
{
cents = cents - 10;
changeowed++;
}
while (cents > 5)
{
cents = cents - 5;
changeowed++;
}
while (cents > 1)
{
cents = cents - 1;
changeowed++;
}
printf("%i \n", changeowed);
}
Here's the problem: There are 4 loops, one for quarters, one for dimes, one for nickels, and one for pennies. The first loop condition is correct:
while (cents >= 25)
The other three are incorrect:
while (cents > 10)
while (cents > 5)
while (cents > 1)
These all need to be changed to use >= in place of >.
you can do it much simple for any nominals. Use integer types.
int nominals[] = {100, 25, 10, 5, 1, 0};
void getNominals(double money, int *result)
{
unsigned ncents = money * 100.0;
int *nm = nominals;
while(*nm && ncents)
{
*result++ = ncents / *nm;
ncents %= *nm++;
}
}
int main(void)
{
int result[sizeof(nominals) / sizeof(nominals[0])] = {0};
getNominals(4.36, result);
for(size_t index = 0; nominals[index]; index++)
{
printf("%d = %d\n", nominals[index], result[index]);
}
}
https://godbolt.org/z/WdYxxr

Bug in While-Loop Keeps Counting Beyond Condition

For school I am to write a C program that takes some amount of cash and returns the smallest number of coins it would take to reach that amount. I don't know what I am doing wrong. I've been tweaking and trying all sorts of different things but I cannot seem to totally debug the program.
The program gives correct answers to some inputs but overstates the amount of coins needed for many inputs.
Here is what I have so far.
#include <stdio.h>
int main()
{
float cash;
int n;
int counter=0;
int quarters=0;
int dimes=0;
int nickels=0;
int pennies=0;
for (;;)
{
printf("Enter change amount: ");
scanf("%f",&cash);
if (cash > 0)
{
break;
}
}
n = cash * 100;
counter = 0;
while (n > 0)
{
while (n >= 25)
{
counter ++;
n = n - 25;
quarters ++;
printf("%i\n",n);
}
while (n >= 10 && n < 25)
{
counter ++;
n = n - 10;
dimes ++;
printf("%i\n",n);
}
while (n >= 5 && n < 10)
{
counter ++;
n = n - 1;
nickels++;
printf("%i\n",n);
}
while (n > 0 && n < 5)
{
counter ++;
n = n - 1;
pennies ++;
printf("%i\n",n);
}
}
printf("%d\n",counter + n);
printf("%i quarters, %i dimes, %i nickels, %i pennies\n",
quarters, dimes, nickels, pennies);
return 0;
}
I'm a bit surprised they're wanting you to use break to exit a loop, as you usually want loops to conclude "naturally" (and you usually save breaks for switch statements). Something like this should work, using integer division and the modulus operator (edit note: I'm using two ints instead of a single float because of inaccuracy with the latter. If someone more knowledgeable wants to show how to do it with float, would be interesting.):
#include <stdio.h>
int main() {
int dollar, cent;
int q = 0;
int d = 0;
int n = 0;
int p = 0;
int re;
printf("Enter amount: ");
scanf(" %d.%d", &dollar, &cent);
q = dollar * 4;
re = cent;
q = q + (re / 25);
re = re % 25;
d = re / 10;
re = re % 10;
n = re / 5;
re = re % 5;
p = re;
printf("q %d d %d n %d p %d\n", q, d, n, p);
return 0;
}
This approach also works if, for example, you're given the seconds and want to find the min:sec from that. If you're given 65 seconds, you do 65 / 60 for the minutes portion (which is 1), and the seconds portion is just the remainder after you divide by 60, or 65 % 60 (which is 5).
Here is a more complete answer that fits with the code that you gave us to start with. I changed the loops to subtraction/multiplication and fixed the bug where you were treating nickels as pennies. You don't need the counter variable anymore, but I left it in.
#include <stdio.h>
int main()
{
float cash;
int n;
int counter=0;
int quarters=0;
int dimes=0;
int nickels=0;
int pennies=0;
for (;;)
{
printf("Enter change amount: ");
scanf("%f",&cash);
if (cash > 0)
{
break;
}
}
n = cash * 100;
counter = 0;
if (n > 0)
{
quarters = (int)floor(n / 25);
n -= quarters*25;
printf( "%i\n", n );
dimes = (int)floor(n / 10);
n -= dimes*10;
printf("%i\n",n);
nickels = (int)floor(n / 5);
n -= nickels*5;
printf("%i\n",n);
pennies = n;
printf("%i\n",n);
}
printf("%i quarters, %i dimes, %i nickels, %i pennies\n",
quarters, dimes, nickels, pennies);
return 0;
}
First of all, try start with abstracting out how to handle one type of coin:
int coinsNeeded( int amount, int coinAmount )
{
return (int) floor( amount / coinAmount );
}
Then, handle each coin separately:
quarters = coinsNeeded( cash, 25 );
cash -= (quarters * 25);
Just repeat that for each type of coins you want to consider, and then print out the information at the end. There is some disagreement about whether you want to use floating points or not. Floating points do have rounding errors that you want to avoid when using money. what you actually need is a fixed point data type, but I digress. You can get close enough by doing it the way you're doing it (multiplying by 100 and just dealing with pennies).

Weird sum value for CS50 pset1- Greedy challenge

I have finished my code for Greedy challenge in PSET1's CS50
However, the total count of coins returns is quite large. When I look further into it, it seems that my nickels coins count is huge (4381344 coins for 0.48 cent).
Call me stupid but I have been pulling my hair for a while because of this. Anyone can point out why?
#include <cs50.h>
#include <stdio.h>
#include <math.h>
// You want to:
// get user input of a float
// check float
// Loop: minus money with biggest coins unit until negative
// then loop and loop
// until 1
// then count the number of loop (by assign a variable to count)
int main(void)
{
float money_give;
int quarters= 25, qc, dimes = 10, dc, nickels= 5, nc,pennies= 1, pc;
do
{
printf("O hai! How much change is owed?\n");
money_give = get_float();
}
while (money_give <= 0.0);
money_give = money_give * 100;
int money = (int)round(money_give);
while (money >= quarters)
{
qc = money / quarters;
money = money % quarters;
}
while (money >= dimes)
{
dc = money / dimes;
money = money % dimes;
}
while (money >= nickels)
{
nc = money / nickels;
money = money % nickels;
}
while (money >= pennies)
{
pc = money / pennies;
money = money % pennies;
}
printf("%i\n",pc+ nc+ qc +dc);
printf("%i\n",nc);
printf("%i\n",qc);
printf("%i\n",dc);
printf("%i\n",pc);
}
Oh and the output is:
O hai! How much change is owed?
0.48
4381350
4381344
1
2
3
You forgot to initialize your variables. Change:
int quarters= 25, qc, dimes = 10, dc, nickels= 5, nc,pennies= 1, pc;
into:
int quarters= 25, qc = 0, dimes = 10, dc = 0, nickels= 5, nc = 0, pennies= 1, pc = 0;
What happened was that because nc had not been initialized, then it started with being equal to whatever garbage was already there in the memory where it was being stored.
Then when you came to this part, it did not get a new value because money was less than nickels:
while (money >= nickels)
{
nc = money / nickels;
money = money % nickels;
}
Therefore it never got assigned a new value instead of the garbage it started with.
The lesson from this: Always initialize your variables.

C program to calculate change

I am trying to write a program to calculate change, but it doesn't seem to work.
I think that the problem is the owed 1/ paid 1; when I tried to print there values I got nothing (0).
Any help ?
#include <stdio.h>
int main()
{
double owed, paid;
int dollars, quarters, dimes, nickels, cents, remainder, owed1, paid1;
printf("how much did the customer have to pay ?\n");
scanf("%f",&owed);
printf("how much did the customer pay ?\n");
scanf("%f",&paid);
owed1 = owed * 100;
paid1 = paid * 100;
int change = paid1 - owed1;
dollars = change / 100;
remainder = change % 100;
quarters = remainder / 25;
remainder = remainder % 25;
dimes = remainder / 10;
remainder = remainder % 10;
nickels = remainder / 5;
remainder = remainder % 5;
cents = remainder;
printf("%d",dollars);
printf("Dollars:%d, Quarters:%d, Dimes:%d, Nickels:%d, Cents:%d", dollars , quarters , dimes , nickels , cents );
return 0;
}
You're using %f in your scanf, which is the format specifier for a float, but your variables are doubles. You should use %lf instead:
scanf("%lf",&owed);
Same thing for paid. You should be getting warning from your compiler about that.

Resources