#include <stdio.h> int main() { float a = 1234.5f; printf("%d\n", a); return 0; } It displays a 0!! How is that possible? What is the reasoning?
I have deliberately put a %d in the printf statement to study the behaviour of printf.
A computer program is a sequence or set of instructions in a programming language for a computer to execute. Computer programs are one component of software, which also includes documentation and other intangible components.
System software controls a computer's internal functioning, chiefly through an operating system, and also controls such peripherals as monitors, printers, and storage devices.
The purpose of a program provides the framework that sets the direction of the program, while the goals and objectives provide a plan as to how the purpose will be achieved.
That's because %d expects an int but you've provided a float.
Use %e/%f/%g to print the float.
On why 0 is printed: The floating point number is converted to double before sending to printf. The number 1234.5 in double representation in little endian is
00 00 00 00 00 4A 93 40 A %d consumes a 32-bit integer, so a zero is printed. (As a test, you could printf("%d, %d\n", 1234.5f); You could get on output 0, 1083394560.)
As for why the float is converted to double, as the prototype of printf is int printf(const char*, ...), from 6.5.2.2/7,
The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.
and from 6.5.2.2/6,
If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type
floatare promoted todouble. These are called the default argument promotions.
(Thanks Alok for finding this out.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With