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

Time:03-03

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?

CodePudding user response:

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

CodePudding user response:

You see same amount of digits after ., because C rounds off them.

You can fix this issue by setting decimal precision in format specifier in printf() function. ("%0.<LIMIT>lf")

Also, %f is format specifier is for float, use %lf for double.

Like this: TRY IT ONLINE

#include <stdio.h>

int main(void)
{
    double pi = 3.1415926535;
    printf("Before:\n");
    printf("%lf %zu\n", pi,sizeof(pi));
    printf("After:\n");
    printf("%0.10lf %zu", pi,sizeof(pi));
    return 0;
}

Output:

Before:
3.141593 8
After:
3.1415926535 8
  • Related