kraljevocs
kraljevocs

Reputation: 115

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

Upvotes: 2

Views: 14189

Answers (3)

txk2048
txk2048

Reputation: 321

In this case you must use %f, otherwise you will get a strange answer as you saw in your code

Upvotes: 1

John Bode
John Bode

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

user3469811
user3469811

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.

source: https://www.gnu.org/software/libc/manual/html_node/Table-of-Output-Conversions.html#Table-of-Output-Conversions

Other conversions are possible too

Upvotes: 3

Related Questions