Search code examples
ctypesfloating-pointdouble

Why when using printf float and double show the same number of digits?


I wanted to see the difference in how many digits i get when using float and when using double but i get the same results

#include <stdio.h>

int main()
{
    float x=1.2222222222222222f;
    printf("%f %d", x,sizeof(x)); // This is what it prints out 1.222222 4
    return 0;
}
#include <stdio.h>

int main()
{
    double x=1.2222222222222222;  
    printf("%f %d", x,sizeof(x));  // This is what it prints out 1.222222 8
    return 0;
}

It prints out the same value even tho double is obviously double the size and should save more digits. What am i doing wrong?


Solution

  • sizeof returns size_t. To print size_t you need %zu instead of %d

    If you want to see the real difference between float and double you need to print more digits using %.NUMBERf

    Like:

    #include <stdio.h>
    
    int main(void)
    {
        float x=1.2222222222222222f;
        printf("%.70f %zu\n", x,sizeof(x)); 
        double y=1.2222222222222222;  
        printf("%.70f %zu\n", y,sizeof(y)); 
        return 0;
    }
    

    Output:

    1.2222222089767456054687500000000000000000000000000000000000000000000000 4
    1.2222222222222220988641083749826066195964813232421875000000000000000000 8