Dre V
Dre V

Reputation: 33

How do I get my for loop to continue executing when float values are equal?

Right now I'm using C and I came across a problem while doing a certain task. The task is to be able to input a number and the value of coins used will be displayed after. My problem is, say there is 0.10 cents worth of change, my code will skip past the dime loop (which checks if a value of 0.10 is less than the value of the change, then subtracts) and continue on to the nickel.. which will then skip the nickel after the change value goes to 0.05 and goes to pennies, which will then stop at 0.01 and end the coin count making the count one penny short and also longer than needed.

int main(void) {
  float c;

  int k = 0;

  printf("How much change?: \n");
  c = GetFloat();

  //checks for quarters
  for (float q = 0.25; q <= c; k = k + 1) {

    c = c - 0.25;
    printf("q \n");
  }
  //checks for dimes
  for (float d = 0.10; d <= c; k = k + 1) {

    c = c - 0.10;
    printf("d \n");
  }
  //checks for nickels
  for (float n = 0.05; n <= c; k = k + 1) {
    c = c - 0.05;
    printf("n \n");

  }
  //checks for pennies
  for (float p = 0.01; p <= c; k = k + 1) {
    c = c - 0.01;
    printf("p \n");
  }

  printf("%d  & %.02f \n", k, c);
}

I have a clue thinking that the error could be in the condition part of the for loops but I have no clue :/

Upvotes: 2

Views: 179

Answers (1)

Bathsheba
Bathsheba

Reputation: 234695

Your problems are all due to floating point imprecision: binary floating point cannot be precisely converted to and from decimal notation.

It happens that 0.25 can be represented exactly in floating point: as can many of its multiples. But 0.1 cannot. So your incrementing by these amounts will give you unexpected behaviour.

Your best bet in this case is to use integral types throughout and work in cents.

Upvotes: 6

Related Questions