-3

My code for the greedy programme works fine for all numbers so far except for 4.2 . Would really appreciate it if anyone can point out the error

:) greedy.c exists
:) greedy.c compiles
:) input of 0.41 yields output of 4
:) input of 0.01 yields output of 1
:) input of 0.15 yields output of 2
:) input of 1.6 yields output of 7
:) input of 23 yields output of 92
**:( input of 4.2 yields output of 18
   \ expected output, but not "22\n"**
:) rejects a negative input like -.1
:) rejects a non-numeric input of "foo"
:) rejects a non-numeric input of ""

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

int main(void)
{
   float x;
  do
 {
     printf("how much change is owed(in dollars)?:\n");
     x = GetFloat();
 }
  while (x < 0);


  x = x*100;
  int i = 0;
 while (x >= 25)
 {
    x = (x-25);
    i++;
 }


  while (x >= 10)
 {
    x = (x-10);
    i++;
 }

 while (x >= 5)
 {
    x = (x-5);
    i++;
 }

 while (x >= 1)
 {
    x = (x-1);
    i++;
 }
 printf("%d\n",i);
}
ysth
  • 96,171
  • 6
  • 121
  • 214
  • 4
    Please see [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken). Better, work with `int` values. There are numerous "change" questions on SO which exhibit this problem. So far from being "unusual" it is a stage you go through. – Weather Vane Sep 03 '16 at 20:00
  • Never use floating point if you need precise values. – too honest for this site Sep 03 '16 at 20:07

3 Answers3

0

Change the following line

x = x*100;

into

x = floor(x*100); printf("rounded value: %f\n", x);

It will print rounded value: 419 and for that 22 is the right answer. (16x25 + 1x10 + 1x5 + 4x1)

That's what's happening now, as the value that is stored in x is close to 420 but a little bit smaller.

0

This bug has to do with the floating point imprecision, run the following code and you see what's really happening under the hood:

float x = 4.2;
printf("%.50f\n", x);

So instead it's best to first convert the value to a positive integer corresponding to the full value of cents (remember that $4.2 is the same of 420 cents), and do the calculations with this value (and don't forget to round the value first).

VicoSpacorum
  • 1
  • 1
  • 1
0

There is always an imprecision in float numbers. Therefore it is recommended that we convert float to int. You can do so by int amount = lroundf(change*100); also note that the value is multiplied by a 100 times. This is to get rid of the cents, and then round off those unwanted values using the 'lroundf' command.

Xavier Tan
  • 53
  • 8