
December 10th, 2012, 09:39 AM
|
 |
Contributing User
|
|
Join Date: Jan 2003
Location: USA
|
|
|
To explain further what's going on.
scanf reads the input and converts what it reads according to the format string. If the conversion is successful, then it takes the address that it's been given and stores the converted value there for however many bytes long that converted value's type, as specified by the format string.
scanf knows nothing at all about the datatype of the variable whose address you have given it. All that scanf knows about the datatype is what you have told it in the format string. If you give it the address of a double variable, but in the format string tell it that it's a float type instead, then it will only store a float at that address.
As I recall off the top of my head, a float is 4 bytes long and a double is 8 bytes long. All you stored in n was four bytes, leaving the remaining four bytes unchanged from the garbage left in those memory locations. As a result, your program interpreted the resultant garbled mess as an off-the-wall value.
|