0

Beginner here, and I feel like I am so close to solving this problem but for some reason whenever I run my code, it just keeps asking me over and over again to enter how much change I am owed and doesn't print the amount of coins

The Problem:

Write, in a file called cash.c in ~/workspace/pset1/cash/, a program that first asks the user how much change is owed and then spits out the minimum number of coins with which said change can be made

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

int main(void)
{
    float x;
    int coin_amount = 0;
    do
    {
        x = get_float("how much change is owed: $");
    }
    while (x < 0);

    while (x >= .25)
    {
        coin_amount += 1;
        x = x - .25;
    }
    while (x >= .10 && x < .25)
    {
        coin_amount += 1;
        x = x - .10;
    }
    while (x >= .05 && x < .10)
    {
        coin_amount += 1;
        x =  x - .05;
    }
    while (x >= .01 && x < .05)
    {
        coin_amount += 1;
        x = x - .01;
    }
    while (x < .01)
    {
        coin_amount = coin_amount;
    }
    printf("I have %i coins to give you in change\n", coin_amount);
}

Any idea's in what I am doing wrong? Thank you :)

Ali Halawa
  • 1
  • 1
  • 5

1 Answers1

0

The main issue with your solution is that the final while() loop - once entered - can not be exited. There are a few other small issues however:

  • You should be using return 0; to provide a return value for int main(void)
  • while (x >= .10 && x < .25) and friends are redundant: you can just use while (x >= .10) (since the second condition has already been satisfied in the previous while() loop
  • You can use x -= .25 instead of x = x - .25 (not important and a matter of preference)

Bearing these points in mind, you can try the following ...

#include <stdio.h>

int main(void) {
    float x = 0.0;
    int coin_amount = 0;

    printf("Enter the currency amount: ");
    scanf("%f", &x);
    printf("You entered: %.4f\n", x);

    while (x >= .25) {
        coin_amount += 1;
        x -= .25;
    }
    while (x >= .10) {
        coin_amount += 1;
        x -= .10;
    }
    while (x >= .05) {
        coin_amount += 1;
        x -= .05;
    }
    // Use .00999 instead of .01 due to quirks with floating point math
    while (x >= .00999) {
        coin_amount += 1;
        x -= .01;
    }
    if (x > 0) {
        printf("Ignoring residual value - %.4f ...\n", x);
    }
    printf("I have %i coins to give you in change\n", coin_amount);

    return 0;
}

You haven't specified what your get_float() function is, so I have used scanf() instead.

As Yunnosch initimated in his comment reply, it might be worth considering a solution which doesn't use floating point math also.

David Collins
  • 2,852
  • 9
  • 13