1

This program have to count minimum number of coins, but it has some kind of bug because results are weird. It`s probably obvious mistake but I cant find it.

int main(int argc,char* argv[]){
      float x;
      printf("How much cash in float number:");
      scanf("%f", &x);

      int quaters;
      while(x>=0.25){
        x-=0.25;
        quaters++;
      }
      printf("%f\n",x);

      int fives;
      while (x>=0.05){
        x-=0.05;
        fives++;
      }
       printf("%f\n",x);

      int one;
      while (x>=0.01){
        x-=0.01;
        one++;
      }
       printf("%f\n",x);
      printf("quaters %d\t fives %d\t ones %d\n", quaters, fives, one);
      return 0;
    }

And the output is this

    How much cash in float number:0.41
0.160000
0.010000
0.010000
quaters 1    fives 3     ones 32764

What`s wrong?

shabat
  • 25
  • 1
  • 6
  • 1
    Where and how do you initialze `quarter`, `fives`, `ones`? And [tag:C++] and [tag:C] are not the same thing! this is just [tag:C]. – RedX Sep 22 '15 at 07:35
  • 2
    When dealing with cash, it's usually better to tink in terms of pennies and use integers, so 101 cents rather than 1.01 dollars. That will get rid of the issues with floating-point comparison. – M Oehm Sep 22 '15 at 07:35

4 Answers4

0

You need to initialize quaters, fives and one to 0 before using it:

int quaters=0;
....
int fives=0;
....
int one=0;
....

Regarding the last 0.01 result, google for "comparing float variables C++". Even here in SO you will find plenty of related posts.

For immediate solution, since you use up to 2 digits after the decimal point, change float compare from

x>=0.25

to

x>0.249

And all the others accordingly:

x>0.049

x>0.009
Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
0
int quaters;
int fives;
int one;

quaters fives and one is uninitialized which will lead to undefined behavior

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

quarter ,five and one are uninitalized . Initialize them to 0.

Also in comparisons -

  while(x>=0.25){        // x is float and 0.25 is double 
    x-=0.25;

You should not compare float numbers like this .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

Try using small value to compare to hide the error. Let me use EPS here as the small value.

  • a>b -> a>b+EPS
  • a>=b -> a+EPS>b
  • a==b -> fabs(a-b)<EPS (fabs is in math.h)

Also, don't forget to initialize the variables!

#include <stdio.h>

#define EPS (1e-9)

int main(int argc,char* argv[]){
    float x;
    printf("How much cash in float number:");
    scanf("%f", &x);

    int quaters=0;
    while(x+EPS>0.25){
        x-=0.25;
        quaters++;
    }
    printf("%f\n",x);

    int fives=0;
    while (x+EPS>0.05){
        x-=0.05;
        fives++;
    }
    printf("%f\n",x);

    int one=0;
    while (x+EPS>0.01){
        x-=0.01;
        one++;
    }
    printf("%f\n",x);
    printf("quaters %d\t fives %d\t ones %d\n", quaters, fives, one);
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70