I'm new to C programming, but decent in Java, my question is when do we use %d and %f? In what situation? For example, based on the code block given below, if I was asked to take (int)a*(float)y, do I take it as a %d or as a %f?
#include <stdio.h>
int main()
{
int a = 2;
float y= 1.5;
printf("%d \n", a*y); //do I take this?
printf("%f", a*y); //do I take this?
return 0;
}
Output:
745417384
3.000000
For printf, %d expects its corresponding argument to have type int, where %f expects it to have type float or double.
The result of an arithmetic expression involving and int and a float will be float, so you will need to use %f in this case.
‘%d’, ‘%i’: Print an integer as a signed decimal number. See Integer Conversions, for details. ‘%d’ and ‘%i’ are synonymous for output, but are different when used with scanf for input (see Table of Input Conversions).
‘%f’: Print a floating-point number in normal (fixed-point) notation. See Floating-Point Conversions, for details.
source: https://www.gnu.org/software/libc/manual/html_node/Table-of-Output-Conversions.html#Table-of-Output-Conversions
Other conversions are possible too
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