【发布时间】:2019-08-31 15:06:03
【问题描述】:
我正在寻找一种在 C 中打印浮点数的方法,该方法在点后至少打印一个小数,但仍会截断尾随零,例如
double x = 5.0;
printf("<some_format>", x);
// should print 5.0, not 5, and not 5.000000
double y = 5.10;
printf("<same_format>", y);
// should print 5.1, not 5.10, and not 5.100000
double x = 5.1230;
printf("<same_format>", z);
// should print 5.123, not 5.1230
另外,定义最大或固定数量的数字/小数正是我想要避免的。
有人知道使用printf 完成此操作的一种格式,而无需将数字写入字符缓冲区然后手动编辑此缓冲区?
【问题讨论】:
-
你试过什么?您的尝试是如何奏效的?
-
带有 %g 和 %f 的标准内容,并阅读了 printf 的手册页,我没有看到任何关于此问题的信息。
-
这真的很难,如果不是不可能的话,因为真的没有办法知道一个浮点值到底有多少个小数。
标签: c string printing terminal printf