c++ - C - Printing a float - loss of precision when casting to int -



c++ - C - Printing a float - loss of precision when casting to int -

this question has reply here:

precision of floating point 7 answers

i'm trying create function enables me print floats. right now, i'm encountering 2 unusual behaviors : sometimes, values 1.3 come out 1.2999999 instead of 1.3000000,and values 1.234567 come out 1.2345672 instead of 1.2345670.

here's source code :

int ft_putflt(float f) { int ret; int intpart; int i; ret = 0; = 0; intpart = (int)f; ft_putnbr(intpart); ret = ft_nbrlen(intpart) + 8; write(1, ".", 1); while (i++ < 7) { f *= 10; ft_putchar(48 + ((int)f % 10)); } homecoming (ret); }

ft_putnbr ok afaik. ft_putchar simple phone call "write(1, &c, 1)".

test values (value : output) 1.234567 : 1.2345672 (!) 1.2345670 : 1.2345672 (!) 1.0000001 : 1.0000001 ok 0.1234567 : 0.1234567 ok 0.67 : 0.6700000 ok 1.3 : 1.3000000 ok (fixed it) 1.321012 : 1.3210119 (!) 1.3210121 : 1.3210122 (!)

this seems bit mystic me... loss of precision when casting int maybe ?

yes, lose precision when messing floats , ints.

if both floats have differing magnitude , both using finish precision range (of 7 decimal digits) yes, see loss in lastly places, because floats stored in form of (sign) (mantissa) × 2(exponent). if 2 values have differing exponents , add together them, smaller value reduced less digits in mantissa (because has adapt larger exponent):

ps> [float]([float]0.0000001 + [float]1) 1

in relation integers, normal 32-bit integer capable of representing values not fit float. float can still store approximately same number, no longer exactly. of course, applies numbers big enough, i. e. longer 24 bits.because float has 24 bits of precision , (32-bit) integers have 32, float still able retain magnitude , of important digits, lastly places may differ:

ps> [float]2100000050 + [float]100 2100000100

c++ c casting output

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

java - Parsing XML, skip certain tags -

c# - ASP.NET MVC Sequence contains no matching element -