在开发跨平台计算器应用程序时,我刚刚注意到在 W32 上 NaN/Inf 值转换为字符串的方式与在 OSX/linux 上不同。 即。
linux/OSX 使用 nan
rsp inf
,而 W32 使用类似 1.#INF
的东西。 1.#QNAN
.
在所有平台上获得相同表示的规范方法是什么?
我想避免使用 isnan()
和 isinf()
手动检查值,并避免对 inf
resp nan 进行硬编码
字符串表示。
(我在 What is the difference between IND and NAN numbers 中读到一些评论说真正的“罪魁祸首”是 libc 实现,而不是平台)。
最佳答案
在 C11(可能更早)中,这些表示由规范强制执行,至少部分强制执行。来自 ISO/IEC 9899:2011,7.21.6.1 fprintf
函数部分,第 8 段:
A
double
argument representing an infinity is converted in one of the styles[-]inf
or[-]infinity
— which style is implementation-defined. A double argument representing a NaN is converted in one of the styles[-]nan
or[-]nan(
n-char-sequence)
— which style, and the meaning of any n-char-sequence, is implementation-defined. TheF
conversion specifier producesINF
,INFINITY
, orNAN
instead ofinf
,infinity
, ornan
, respectively.
除此之外,恐怕你要靠自己了。
关于c - 我如何让 printf 在 w32 上使用 'nan'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43333192/