0

I am trying to separate the numbers in a floating input (xx.yy) and extract them out. Not so sure if this is the online compiler fault but for some reasons, there are times when I run my following code, the decimal places that I extract seemingly -1 in value.

I am using this online compiler (https://repl.it/languages/c).

#include <stdio.h>

int main()
{
    int whole_num = 0;
    int dec_num = 0;

    float u_input = 0.0;
    printf("Input in a float: ");
    scanf("%f", &u_input);

    whole_num = (int) u_input;
    printf("1. Whole number is %d\n", whole_num);

    dec_num = (u_input - whole_num)*100;
    printf("2. Decimal number is %d\n", dec_num);

    return 0;

}

For example, there are times when I input in 99.95, instead of expecting 95 for my dec_num, it gave me 94. Then again, if I used another input such as 123.95 it returns me 95 instead. And as a result, if my code is giving me the -1 result, it will fails in other parts of my code.Decimal

I can't find out if it is an error with the way I have written my code and/ or if it is an issue with the compiler (also tried it with other online compilers which seemingly giving me similar results)

Can anyone share any insights to me on this? Or if there is a proper method that I will get the decimal number I expected without the -1?

k_plan
  • 121
  • 1
  • 7
  • You're experiencing floating point inexact effects. You probably need to apply some rounding to your calculations. – Tom Karzes Apr 09 '20 at 04:54
  • @TomKarzes without the use of `#include ` or `round`, I guess I am unable to derive the expected result that I wanted based on my above code? – k_plan Apr 09 '20 at 05:05

1 Answers1

0

Floating point numbers are represented using binary notation (see https://en.wikipedia.org/wiki/IEEE_754).

As such, decimal numbers that do not have an exact binary representation are stored as an approximation to the desired values.

For example, a value like 1.25 has an exact binary representation (5*(2^-2)), while numbers like 1.3 do not and need to be apprximated.

This website offers a good visualization of this phenomenon.

rtx13
  • 2,580
  • 1
  • 6
  • 22