0

Sorry if this is a noob question but I'm new to C. I was working on a problem of changing a float to an int (request a float from the user but return it as an int). I thought I had the solution by multiplying by 100 but I found that if the user enters .59 as their input and multiplies it by 100, the result is 58. I tried to find the solution to why this was happening but couldn't. Does anyone know why this happened and how to fix it? I'll leave the code below:

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

int main(void)
{
  float money;
  do 
  {
    printf("How much change is owed?: ");
    money = GetFloat();
  }
  while (money<0);
  int x = money * 100;
  if (money >= .25) 
  {
    printf("%f times 100 = %d\n", money, x);
  }
}

Here is the result:

How much change is owed?: .59 
0.590000 times 100 = 58
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Mek
  • 1
  • 1
  • http://floating-point-gui.de/ – Fildor Feb 06 '17 at 15:19
  • 4
    It is best to avoid using floating point variables for "change" problems. A very quick answer: just as you cannot represent one-third exactly in decimal, so in binary you cannot accurately represent one-tenth. – Weather Vane Feb 06 '17 at 15:20

0 Answers0