0

i am trying to get decimal part of reel number and assign it to int variable.

float x= 1.4, y, z;
y=x-(int)x;
z=y*10;
int a;
a=z;
printf("\n y : %.10f \n a : %d\n", y, a);

output : y : 0.3999999762 a : 3

why it is not y: 4.0000000000 and a : 4 ?

bashburak
  • 105
  • 1
  • 5
  • If you are only interested in the integer value `a`, you can use `a = round(z);` instead of `a = z;`. Don't forget `#include `. – Jabberwocky May 04 '18 at 15:59
  • how function round() do that, i want to understand it, using function might be the simple way. what is in round() function. for a small code i will use whole math.h library. instead i will create my own b_round() function – bashburak May 04 '18 at 16:04
  • 1
    Note that 4 can be represented *exactly* in a `float`, but some of the values you use in the earlier calculations cannot. – Dmitri May 04 '18 at 16:05
  • @bashburak if you use `round`, only the `round` function and the functions used by `round` will be linked to your binary. Making a `round` function yourself is not as simple as it appears to be. See this [SO article](https://stackoverflow.com/questions/22836212/source-code-to-round-floating-point-number) – Jabberwocky May 04 '18 at 16:08
  • @bashburak If you want to do the rounding yourself, the simple way is with something like `a = (int)(z + 0.5)`. But that won't work as well for negative numbers. – Steve Summit May 04 '18 at 16:10
  • @EricPostpischil Why are you directing this at me? I said nothing about how `round` is implemented, and you seem to agree that 4 can be represented exactly. OP's issue comes from inexact representations of other numbers (like 1.4), in the calculation that was supposed to result in 4. – Dmitri May 04 '18 at 19:44
  • @Dmitri: Sorry, my second comment was intended for OP, and I misread your comment. I was on a small mobile device. I’ll delete the first and correct the second. – Eric Postpischil May 04 '18 at 20:26
  • @bashburak: `round` is implented either with a hardware instruction specifically for that purpose, or with floating-point instructions while being careful to use properties of floating-point operations precisely, or by manipulating the internal representation of floating-point data. A proper explanation requires some introductory material about floating-point arithmetic. – Eric Postpischil May 04 '18 at 20:26
  • In particular, the closest IEEE 754 32-bit binary float to 1.4 is 1.39999997615814208984375. The root cause of the results is already present in the initialization of `x`. – Patricia Shanahan May 05 '18 at 00:09

0 Answers0