floating point - Pi in C language -


so trying value of pi in c (ide = dev c++) using long double in , result giving me complete set of zeros here program

int main()  {     long double rootof3;      rootof3 = (22.0/7.0);      printf("%lf", rootof3);     system("pause");     return 0; } 

after found out value of pi not precise in c , declared in math.h , when tried value code

int main()  {      printf("%f", m_pi);     printf("%e", m_pi);     printf("%lf", m_pi);     system("pause");     return 0; } 

i these value

3.1415933.141593e+0003.141593press key continue . . . 

so questions

1) mistake in first program , can values of pi above code using long double
2)is true in c value of pi not accurate?an why not getting entire pi value assigned in math.h

thanks

for printing long double, use "%lf". use of "%lf" 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 op's comment

it's difficult see how accurately number represented using float, double, , long double using default settings in printf. using format prints more digits after decimal point, differences 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 

Comments