'sprintf': double precision in C

后端 未结 3 887
南笙
南笙 2021-01-04 01:22

Consider:

double a = 0.0000005l;
char aa[50];
sprintf(aa, \"%lf\", a);
printf(\"%s\", aa);

Output: s0.000000

In the above code snippet, th

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 02:13

    The problem is with sprintf

    sprintf(aa,"%lf",a);
    

    %lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:

    sprintf(aa, "%f", a);
    

    More details here on cplusplus.com

提交回复
热议问题