‘sprintf’:C中的双精度

考虑:

double a = 0.0000005l; char aa[50]; sprintf(aa, "%lf", a); printf("%s", aa); Output: s0.000000 

在上面的代码片段中,变量aa只能包含六位小数。 我想获得像“s0.0000005”这样的输出。 我该如何实现这一目标?

从您的问题看来,您似乎正在使用C99,因为您使用%lf来表示双倍。

要实现所需的输出替换:

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

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

一般语法"%AB"表示使用小数点后的B位数。 A的含义更复杂,但可以在这里阅读。

你需要像sprintf(aa, "%9.7lf", a)一样写它sprintf(aa, "%9.7lf", a)

有关格式代码的更多详细信息,请访问http://en.wikipedia.org/wiki/Printf 。

问题出在sprintf上

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

%lf称interpet“a”为“long double”(16字节),但实际上是“double”(8字节)。 改为使用它:

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

有关cplusplus.com的更多详情