aspose file tools*
The moose likes C / C++ and the fly likes Issues in understanding output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "Issues in understanding output" Watch "Issues in understanding output" New topic
Author

Issues in understanding output

Rachit Kumar Saxena
Ranch Hand

Joined: Dec 24, 2011
Posts: 50
printf("%9d",9.6); gives a warning(I understand the warning) but the output is 858993459.Why?Please explain in terms of the memory architecture(I use a 32 bit system).
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14345
    
  22

9.6 is a double literal. It's stored in memory in IEEE 754 double precision format. The printf function is going to interpret it as an integer, since you used d for the type.

The value 9.6 in double precision format looks like 858993459 when you interpret it as an integer.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Anand Hariharan
Rancher

Joined: Aug 22, 2006
Posts: 257

Jesper's answer is correct. Just wanted to clarify one statement in his post -
It's stored in memory in IEEE 754 double precision format.

Unlike Java, the language standards for C or C++ does not require the underlying implementation/hardware to use a floating point representation that conforms to the IEEE 754. However in practice, for the OP who uses a 32 bit system, and most other conventional desktops or laptops indeed conform to the IEEE 754 standard.

The takeaway is that, if one writes code that implicitly assumes a certain representation (like the OP's code for example), the C and C++ standards disavow such code claiming "undefined behaviour". This is because the interpretation of the underlying floating point representation as an integer could have unexpected weird effects in esoteric hardware (e.g., it could be a trap instruction).

Pay heed to the warnings!

- Anand


"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exupery
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Issues in understanding output