Ruslan Ver
Ruslan Ver

Reputation: 137

Why is the output different using printf?

In some places the command printf("%f\n", 5 / 2); is different. Why, and how to fix that?

int main()
{
    int a = 65;
    char c = (char)a;
    int m = 3.0/2;
    printf("%c\n", c);              // output: A
    printf("%f\n", (float)a);       // output: 65.000
    printf("%f\n", 5 / 2);          // output: 65.000
    system("PAUSE");
    printf("%f\n", 5.0 / 2);        // output: 2.5000
    printf("%f\n", 5 / 2.0);        // output: 2.5000
    printf("%f\n", (float)5 / 2);   // output: 2.5000
    printf("%f\n", 5 / 2);          // output: 2.5000
    system("PAUSE");
    printf("%f\n", 5 / (float)2);   // output: 2.5000
    printf("%f\n", (float)(5 / 2)); // output: 2.0000
    printf("%f\n", 5 / 2);          // output: 2.0000
    system("PAUSE");
    printf("%f\n", 5.0 / 2);        // output: 2.5000
    printf("%d\n", m);              // output: 1
    printf("%f\n", 5 / 2);          // output: 2.5000


    system("PAUSE");
    return(0);
}

Upvotes: 0

Views: 757

Answers (1)

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27652

5/2 gives an integer as result, not a floating-point number, and printf cannot automatically convert to another type, as an assignment can. If you compile with GCC, you'll get the warning "format '%f' expects argument of type 'double', but argument 2 has type 'int'". (Yes, double. All floats are converted to doubles before being sent to a variable-argument function like printf.)

The argument you have sent, an integer, doesn't match the format string %f. According to the C standard, this will cause what it calls "undefined behaviour", which means that anything can happen. What typically happens, though, is that printf will look at the place in memory where the floating-point number would have been, if you had sent one as an argument, and take whatever it finds there and interpret it as a floating-point number. Since a typical int is 32 bits, and a typical double is 64 bits, printf will take some other data, perhaps the number 65 from a previous call!

To fix the problem, send a floating-point number to printf, for example using 5.0/2, (double)5/2 or 2.5 instead of 5/2.

Upvotes: 3

Related Questions