math - In C, why is the ratio 10.0/100 different from 0.1? -


this question has answer here:

this simple question , searched forums, couldn't find answer (i found 1 log don't think there rounding error here).

i wrote program determine value of fine range of expired products, when ratio exact, program return next fine category, ignoring = sign in conditional.

the program must return following fines:

  • 0 if no product expired.
  • 100 if 10% of products expired.
  • 10000 if more 10% of products , 30% expired.
  • 100000 if more 30% of products expired.

this code wrote:

#include <stdio.h> int calculate_fine(int ncheckedproducts, int nexpiredproducts) {     int fine;     float ratio;     ratio=(float)nexpiredproducts/ncheckedproducts;      if(nexpiredproducts==0)         fine=0;     else          if(ratio<=0.1)             fine=100;         else              if(ratio<=0.3)                 fine=10000;             else                 fine=100000;      return fine; }  int main(void) {     int ncheckedproducts, nexpiredproducts, fine;     printf("type number of checked , expired products\n");     scanf("%d %d", &ncheckedproducts, &nexpiredproducts);     fine=calculate_fine(ncheckedproducts, nexpiredproducts);     printf("the fine is: %d\n", fine);     return 0; } 

but values of 100 , 10, , 100 , 30, 10% , 30% of expired products respectively, program return wrong fine.

the teacher failed explain me why, , corrected me following function:

int calculate_fine(int ncheckedproducts, int nexpiredproducts) {     int fine;      if(nexpiredproducts==0)         fine=0;     else          if(nexpiredproducts<=0.1*ncheckedproducts)             fine=100;         else              if(nexpiredproducts<=0.3*ncheckedproducts)                 fine=10000;             else                 fine=100000;      return fine; } 

however, wish know why first 10% ratio greater 0.1, , why cannot use approach.

this is rounding issue, different might think: many finite decimal fractions not have finite binary fraction representation. thus, rounding the closest number representable floating point number of given type happens.


Popular posts from this blog