0

I am trying to learn how to code and I have been stuck on my greedy algorithm for hours. My greedy algorithm is not outputting numbers correctly for example .41 will output 3 instead of 4.

#include <stdio.h>
#include <math.h>
int main(void)
{
    float cents;
    int coinsused=0;
    do{
        cents=get_float("Change Owed: " );
    }
    while (cents<0.00);
    
    for(float quarter=0.25; cents>=quarter; cents-=quarter){
        coinsused++;
    }
    for(float dime=0.10; cents>=dime; cents-=dime){
        coinsused++;
    }
    for(float nickle=0.05; cents>=nickle; cents-=nickle){
        coinsused++;
    }
    for (float penny=0.01; cents>=penny; cents-=penny){
        coinsused++;
    }
    printf("%i\n",coinsused);
}
Bodo
  • 9,287
  • 1
  • 13
  • 29
  • 2
    I suggest you work with integers here. This is a FAQ in StackOverflow, for example there is one in the 'Related' panel on the right. You might like to read [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [Why Are Floating Point Numbers Inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) In particular the fraction `1/10` is not exactly representable in binary floating point arithmetic. – Weather Vane Jul 06 '20 at 18:54
  • After reading `cents` as a float, you should do something like `int cash = round(cents * 100.0)`. The rest of the code should then use integer math, e.g. `for (int quarter = 25; cash>=quarter; ...` – user3386109 Jul 06 '20 at 19:43

0 Answers0