casting: int -> double -> int
-
#include <cassert> #include <limits> int main() { for ( int i = std::numeric_limits<int>::min(); i < std::numeric_limits<int>::max(); ++i ) { double d = i; int s = static_cast<int>( d ); assert( s == i ); } }Mit meiner Hardware und meinem Compiler hält die Assertion, aber ist das vom Standard garantiert? Ich hab zwar reingeguckt, konnte aber nichts finden.
-
Dobi schrieb:
#include <cassert> #include <limits> int main() { for ( int i = std::numeric_limits<int>::min(); i < std::numeric_limits<int>::max(); ++i ) { double d = i; int s = static_cast<int>( d ); assert( s == i ); } }Mit meiner Hardware und meinem Compiler hält die Assertion, aber ist das vom Standard garantiert? Ich hab zwar reingeguckt, konnte aber nichts finden.
Dein double ist von ca -2^53 bis 2^53 noch auf die Zahl genau. Dein int hat nur 32 Bit. Also reichlich Platz. Wird auf PCs auch eine ganze Weile so bleiben.
Nein, der Standard garantiert das bestimmt nicht.
-
OK, danke.
Ich hatte befürchtet, dass Dinge wie42 -> 41.9999999 -> 41passieren könnten.
-
Garantiert sind für double und long double 10 signifikante Dezimalstellen, bzw. mindestends 34 bits für die Mantisse bei binärer Repräsentation (DBL_DIG aus float.h). Praktisch sind 53 Bits für double ziemlich unversell. Solange int nicht mehr als 32 bit hat, ist die Konvertierung also garantiert exakt.