I think my way of solving Greedy is a little unorthodox, but let's leave that for another day. If i'm looking for an answer to $2.11 , it will output 8Q,1D,no nickels and pennies. I am assuming it is because lack of decimals or rounding in my code, but having trouble pinpointing the issue. Can someone please take a look and provide some advice? Much appreciate.

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

int main(void)
    float x,cents;
   printf("how much change?: ");
     x = get_float();
    while (x<=0);

  cents = x*100;

  int q,d,n,p;
 q = cents/25;
 d = (cents-25*q)/10;
 n = (cents-(25*q)-(10*d))/5;
 p = (cents-(25*q)-(10*d)-(5*n)/1);

It's exactly the issue of lack of rounding.

If x is 4.2, for example, x*100 is 419 because 4.2 can't be expressed exactly in binary. It's actually 4.1999999nnnn. When you then multiply by 100 and store in an integer, it will be truncated to 419. That's why the round function exists.

round(x*100) will round the value and give you 420 in that example.


The point of the exercise has been missed - floats are frequently not precisely stored.

If you want to see the problem, try printing cents to a precision of 20 digits after the decimal. Also, for each of your calculations, try first storing the result as a float and print them out to 20 decimals. It should quickly become apparent where the problem lies.

Along with the imprecise storage of floats, there's also the issue of converting from a float (the results of parts of the calculations, or all of the calculation for quarters) to an int. The number is truncated, not rounded, so float 2.999999999 would be stored in an int as 2, not 3.

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

You must log in to answer this question.

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