Search code examples
cfloating-pointpi

Pi in C language


So i was trying to get the value of pi in c (IDE = DEV C++) so i am using long double in this and the result it is giving me is a complete set of zeros here is the program

int main() 
{
    long double rootOf3;

    rootOf3 = (22.0/7.0);

    printf("%lf", rootOf3);
    system("pause");
    return 0;
}

after that i found out that the value of pi is not precise in c and is already declared in math.h and when i tried to get the value with this code

int main() 
{

    printf("%f", M_PI);
    printf("%e", M_PI);
    printf("%lf", M_PI);
    system("pause");
    return 0;
}

i get these value

3.1415933.141593e+0003.141593Press any key to continue . . .

so my questions

1) what is the mistake in the first program and can i get the values of pi with the above code using long double
2)is it true that in c the value of pi is not accurate?an why am i not getting the entire pi value assigned in math.h

thanks


Solution

  • For printing a long double, use "%Lf". Use of "%lf" for long double causes undefined behavior.

    #include <stdio.h>
    
    int main() 
    {
       long double pi = 22.0/7.0;
       printf("%Lf\n", pi);
       printf("%lf\n", pi);
       return 0;
    }
    

    Output:

    3.142857
    0.000000
    

    Update, in response to OP's comment

    It's difficult to see the how accurately a number is represented using float, double, and long double using the default settings in printf. By using a format that prints more digits after the decimal point, the differences will be clearer.

    Program:

    #include <stdio.h>
    
    void test1()
    {
       float pi = 22.0f/7.0;
       printf("=== float ================\n");
       printf("%.25lf\n", pi);
       printf("%lf\n", pi);
    }
    
    void test2()
    {
       double pi = 22.0/7.0;
       printf("=== double ===============\n");
       printf("%.25lf\n", pi);
       printf("%lf\n", pi);
    }
    
    void test3()
    {
       long double pi = 22.0L/7.0;
       printf("=== long double ==========\n");
       printf("%.25Lf\n", pi);
       printf("%Lf\n", pi);
    }
    
    int main(void)
    {
       test1();
       test2();
       test3();
       return 0;
    }
    

    Output:

    === float ================
    3.1428570747375488281250000
    3.142857
    === double ===============
    3.1428571428571427937015414
    3.142857
    === long double ==========
    3.1428571428571428572357888
    3.142857