This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes C / C++ and the fly likes Issues in understanding output Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Languages » C / C++
Reply 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: 48
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
Bartender

Joined: Aug 16, 2005
Posts: 12924
    
    3

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 7 API documentation
Scala Notes - My blog about Scala
Anand Hariharan
Rancher

Joined: Aug 22, 2006
Posts: 252

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://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Issues in understanding output
 
Similar Threads
Mock Exam Question
Generics {probably wrong forum}
overriding methods
Overloading with varargs and array parameters, strange inconsistency?
Run Java code ----- Online