Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use %d and %f in C?

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

like image 412
kraljevocs Avatar asked Jan 01 '26 07:01

kraljevocs


2 Answers

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.

like image 54
John Bode Avatar answered Jan 03 '26 09:01

John Bode


‘%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

like image 23
user3469811 Avatar answered Jan 03 '26 09:01

user3469811