C printf 函数说明符
我需要打印一个 16 位有效数字的浮点值。
现在,当我打印时,它会打印出
2.555556,
当我希望它打印出时: 2.555555555555556 /// 总共 16 位数字
我的 printf 说明符当前是:“%20.18lf”
想法?
I need to print out a float value with 16 significant digits.
Right now when I print, it prints out
i.e 2.555556
when I want it to print out: 2.555555555555556 /// A total of 16 digits
My printf specifier currently is : "%20.18lf"
ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果值的类型为
float
,则小数点后可能不会超过 7 位有效数字。如果它是double
类型,则可以得到大约 15。根据系统的不同,long double
可能不会比double
更精确;在我的系统中,小数点后大约有 17 位有效数字。大多数浮点代码使用类型
double
;float
的精确度要低得多,而且通常速度也不会明显加快。我有点惊讶你得到的是
2.555556
而不是像2.555555582046508789
这样的"%20.18lf"
格式。顺便说一句,
l
(小写 L)不是必需的。double
的格式为"%f"
,printf
的float
参数提升为double
,因此"%f"
对于float
和double
都是正确的。long double
的格式为"%Lf"
。这是我编写的测试程序:
以及我在系统上得到的输出:
If the value is of type
float
, you're probably not going to get more than about 7 significant digits after the decimal point. If it's of typedouble
, you can get about 15. Depending on the system,long double
may be no more precise thandouble
; on mine, I get about 17 significant digits after the decimal point.Most floating-point code uses type
double
;float
is much less precise and often not significantly faster.I'm a little surprised that you got
2.555556
rather than something like2.555555582046508789
with a"%20.18lf"
format.Incidentally, the
l
(lowercase L) is not necessary. The format fordouble
is"%f"
, andfloat
arguments toprintf
are promoted todouble
, so"%f"
is correct for bothfloat
anddouble
. The format forlong double
is"%Lf"
.Here's a test program I wrote:
and the output I got on my system:
以下代码运行良好(您必须启用 C99,因为
%lf
说明符不是早期标准的一部分):打印以下内容:
如果值较短,例如 2.5,则会用零向右填充 -
2.500000000000000000
。所以你在其他地方有错误。一般来说,您必须发布一个最小的自洽代码示例来重现问题。否则你就只能靠自己了。
The following code works well (you have to enable C99 as
%lf
specifier is not part of earlier standards):Prints the following:
If value is shorter, say 2.5, it right-pads it with zeros -
2.500000000000000000
.So you have an error elsewhere. Generally, you have to post a minimal self-consistent code example that reproduces the problem. Otherwise you are on your own.
C float或double不够精确,基本上你需要一个高精度的除法函数。这是我写的。它用于整数除法。您可能需要修改它以进行浮点除法。
C float or double is not precise enough, basically you need a high precision division function. Here is what I wrote. It is for integer division. You may need to revise it for float division.