#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    4
    Rep Power
    0

    Difference between float and double


    Hey guys. I was trying to solve a problem for which I needed to use float/double.

    This was my program:

    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main()
    {
         float n;
         while(scanf("%f", &n)&&n)
         {
              printf("%.6f\n", sqrt(2)*n/4);
         }
         return 0;
    }
    The values the previous programs prints on the screen are correct. However, float doesnt offer the precision I need; I decided switch double

    #include <stdio.h>
    #include <math.h>

    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main()
    {
         double n;
         while(scanf("%f", &n)&&n)
         {
              printf("%.6f\n", sqrt(2)*n/4);
         }
         return 0;
    }
    This program returns extremely large values. Any idea on how I could correct it?

    Also my program doesn't want to close after typing 0. Suggestions?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    San Francisco Bay
    Posts
    1,939
    Rep Power
    1313
    You need to use "%lf", not "%f", to read a double with scanf.
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,157
    Rep Power
    2222
    To explain further what's going on.

    scanf reads the input and converts what it reads according to the format string. If the conversion is successful, then it takes the address that it's been given and stores the converted value there for however many bytes long that converted value's type, as specified by the format string.

    scanf knows nothing at all about the datatype of the variable whose address you have given it. All that scanf knows about the datatype is what you have told it in the format string. If you give it the address of a double variable, but in the format string tell it that it's a float type instead, then it will only store a float at that address.

    As I recall off the top of my head, a float is 4 bytes long and a double is 8 bytes long. All you stored in n was four bytes, leaving the remaining four bytes unchanged from the garbage left in those memory locations. As a result, your program interpreted the resultant garbled mess as an off-the-wall value.

IMN logo majestic logo threadwatch logo seochat tools logo