1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

int and float anomalities. Please Help !!

Discussion in 'C' started by Pradeep.M, Feb 1, 2012.

  1. Pradeep.M

    Pradeep.M New Member

    Joined:
    Feb 1, 2012
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    India
    Following is the programme:

    #include<stdio.h>
    int main()
    {
    int a=2;
    float b=2.5;
    printf("a: %d %f %d \n",a,a,a);
    printf("b: %d %f %d \n",b,b,b);
    printf("with f: %f with c:%c\n",150,150);
    getch();
    return 0;
    }
    OUTPUT( on gcc compiler)
    a: 2 0.000000 148
    b: 0 0.000000 1074003968
    with f: 0.000000 with c:


    MY DOUBT:
    :confused:
    the value 2 is printed correctly but 0 is printed with %f is used for int. No problem till here, but after this why 148 is printed. also, in the 2nd line, when %d is used for float variable , 0 is printed , no problem, but then why after that 0.000000 is printed even when %f is used for float...
    in the end.. when I want to print the character corresponding to the ANSCI value 150 using %f.. 0 is printed and when using %c , nothing is printed

    PLEASE clarify, with an example.
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Before the first printf, add the following line and show us the new complete output:
    Code:
    printf("sizeof(int)=%d; sizeof(float)=%d\n", sizeof(int), sizeof(float) );
    
    But basically, this is because you're not using the correct format codes. Use %d for int AND NOTHING ELSE, and use %f for float AND NOTHING ELSE. They must match, otherwise you get undefined behaviour.
     

Share This Page