Jak dziala printf?

0
#include<cstdio>
 
union test
{
  float f;
  int d;
};
 
int main()
{
  float f = 2.34f;
  // dla pewnosci
  printf("%d\n", sizeof(float));
  printf("%d\n", sizeof(int));
 
  test a;
  a.f = f;
  // w jaki sposob printf dochodzi do pierwszej z tych wartosci?
  printf("%d\n", f);
  printf("%d\n", *reinterpret_cast<int*>(&f));
  printf("%d\n", a.d);
  printf("%d\n", (int)f);
  return 0;
}

output:

4
4
-536870912
1075167887
1075167887
2
0

Tobie nie chodzi o printf, tylko o unię ;)

0

o printf, skad on wzial ten ujemny wynik. unia to jest jeden ze posobow w jaki probowalem do niego dojsc

0

Pewnie problem polega na binarnej reprezentacji liczby zmiennoprzecinkowej, http://www.h-schmidt.net/FloatConverter/IEEE754.html - 2.34 nie da się dokładnie zapisać. Przy wypisywaniu tej liczby jako int (%d) źle interpretujesz jej binarną wartość.


edit:

http://www.velocityreviews.com/forums/t548239-p2-printf-d-float.html - zobacz ten temat ;)

[...]
As others have said, or tried to say, using the "%d" format specifier in
printf() does not convert the value of (a) to an int, and casting the
pointer &a to an int * does not change the value stored there into an
int. In both cases, what (usually) happens is that the bit pattern is
interpreted as an int. In other words, instead of translating to an
int, these cases merely point to the bit pattern of a float and say
that it's an int.

To convert the value of (a), you'd use something like

printf( "%d\n", ( int ) a );
[...]

0

-536870912 = -2^29

2

Wszystko fajnie, ale przecież jemu chodzi o to, że wyniki powinny być te same. A nie są.

Jest to spowodowane tym, że jako vararg nie można przekazać float. W tej linijce:

printf("%d\n", f);

float jakim jest f jest konwertowany do double. (Standard C++11 5.2.2.7)

To co widzisz to 32 bity reprezentacji double tej liczby:
Liczba -536870912 w kodzie U2 oraz 2.34f skonwertowane (precyzji się tu nie zyskuje) do double wyglądają tak samo:
11100000000000000000000000000000 (tzn. dolne 32 bity)

W pozostałych przypadkach jako vararg przesyłany jest int i widzisz poprawną reprezentację float.

1 użytkowników online, w tym zalogowanych: 0, gości: 1