Reputation: 115
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
Upvotes: 2
Views: 14189
Reputation: 321
In this case you must use %f, otherwise you will get a strange answer as you saw in your code
Upvotes: 1
Reputation: 123448
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.
Upvotes: 5
Reputation: 678
‘%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.
Other conversions are possible too
Upvotes: 3