-3

Can someone please help me and tell me why the output here is 0.000000 when it supposed to be 2.500000? Its only like that when i put it the first line of print commands, if its in the middle of the print group its going well and goes out 2.500000.. So why its 0? for screenshot click here

#include <stdlib.h>
#include <stdio.h>


int main()
{
    int a = 65;
    char c = (char)a;
    int m = 3.0/2;

    printf("%f\n", 5 / 2);
    printf("%c\n", c);              // output: A
    printf("%f\n", (float)a);       // output: 65.000
    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 / (float)2);   // output: 2.5000
    printf("%f\n", (float)(5 / 2)); // output: 2.0000
    printf("%f\n", 5.0 / 2);        // output: 2.5000
    printf("%d\n", m);              // output: 1



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

Thanks , Tom.

Tom Bazak
  • 11
  • 3
  • You're passing an int when you've told `printf` to expect a double. – user2357112 Nov 18 '15 at 19:04
  • 1
    Reminded me a lot of [Moving printf to different lines gives different outputs? (C)](http://stackoverflow.com/questions/33692356/moving-printf-to-different-lines-gives-different-outputs-c). Are you the same person? – MicroVirus Nov 18 '15 at 19:05
  • @MOehm Yeah it wasn't a duplicate call per se, it's just that the codes match up, right down to the `5/2` and `int a = 65`, I am just wondering why. – MicroVirus Nov 18 '15 at 19:12
  • 1
    @MicroVirus: [Here's another "duplicate" from yesterday.](http://stackoverflow.com/questions/33766748/why-is-the-output-different-using-printf) Lots of people using SO for their schoolwork, as usual. – Blastfurnace Nov 18 '15 at 19:19

1 Answers1

1

In your first line, when you divide integer 5 by integer 2, the computer does integer division, which discards the remainder, giving 2 (not 2.5). The result is an integer, but you try to print it using %f, which is why you saw 0 and not 2.


In answer to your second question: when you pass a plain int to printf but tell it to print it using %f, printf basically takes random garbage from the stack to flesh out the rest of the floating-point number it's trying to print. Whatever random garbage it finds on the stack depends (among other things) on what other functions you've been calling recently. When you moved your printf call to the middle, it was pure luck that the random garbage happened to line up and give a semi-meaningful result.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103