1

I am experiencing some unexpected behavior while working on a program in C that converts money to coins. As can be seen in the output block below in the last 3 printf() outputs the pennies are 0, 1.000000 and 0.

As a C newbie I do not quite get as to why the int pennies_int = remainder / 0.01; code return 0 while the float pennies_float = remainder / 0.01; returns 1.000000. Even casting the float value to an int results in a 0 value.

Could someone explain to me why the float 1.000000 value is not cast to an int 1 while it clearly contains 1?

I am using Ubuntu clang version 3.6.0 and tested the same code on Codepad with the same results.

Code

#include <math.h>
#include <stdio.h>

int main (void)
{
    float cash = 0.41;
    float remainder;

    int quarters = cash / 0.25;
    remainder = fmod(cash, 0.25);

    int dimes = remainder / 0.10;
    remainder = fmod(remainder, 0.10);

    int nickels = remainder / 0.05;
    remainder = fmod(remainder, 0.05);

    int pennies_int = remainder / 0.01;
    float pennies_float = remainder / 0.01;

    printf("Quarters: %i\n", quarters);
    printf("Dimes: %i\n", dimes);
    printf("Nickels: %i\n", nickels);
    printf("Pennies (int): %i\n", pennies_int);
    printf("Pennies (float): %f\n", pennies_float);
    printf("Pennies (casted to int): %i\n", (int) pennies_float);
}

Output

Quarters: 1
Dimes: 1
Nickels: 1
Pennies (int): 0
Pennies (float): 1.000000
Pennies (casted to int): 0
pvg
  • 2,673
  • 4
  • 17
  • 31
mvdgun
  • 262
  • 5
  • 15

0 Answers0