0

I've put together a solution to the problem set Cash using division. When I run the program, it returns incorrect number of coins for most of the cases, e.g. change 61 - 244 coins, change 0.80 - 14 coins but it returns a correct value for change 0.25 (1 coin). I would be grateful for any hints.

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
    int coins;
    float change;

    // Get user's input
    do
    {
        change = get_float("What is the change? ");
    }
    // Condition for the input
    while (change < 0);

// Round dollars to cents
change = round(change * 100);

// Calculate coins

{
    int q = change / 25;
    int d = (change - (25 * q)) / 10;
    int n = (change - ((25 * q) + (10 * d))) / 5;
    int p = (change - (25 * q) + (10 * d) + (5 * n)) / 1;
    coins = q + d + n + p;

printf("Number of used coins: %i\n", coins);
}
}
  • If that approach is not working for you, maybe you could try with some if, else if and else conditional solution. Working with them will help you to get comfortable for using them in the future. – Tritum Apr 27 at 20:58
  • Observe the difference between the parenthetical expressions for d and n compared to p. – DinoCoderSaurus Apr 27 at 22:01
  • Thanks for the hint. How could I have missed it! – MonikaMarch Apr 28 at 9:44
  • @Tritum I know I should try and solve it with if, else if rather than basic maths. I tried but it didn't work at all :/ – MonikaMarch Apr 28 at 9:44
0

It's an efficient approach and you're on the right track! The problem is that it's calculating the total number of each type of coin required, but not accounting for the previous calculations.

Simply put, after accounting for the total number of quarters, the code needs to subtract the value of the quarters from the total before calculating dimes, and so on.

However, even after you fix this, you have another problem waiting in the wings, but one question/problem gets one answer. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |
  • Thanks, I adjusted my calculations and the code was accepted. Assignment submitted :) By another problem you probably meant the missing brackets in int p. All fixed now. – MonikaMarch Apr 28 at 9:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .