c - %g 在 printf 中的工作原理

标签 c

%g 描述说

Use the shortest representation: %e or %f

例如, 如果使用 %.6g544666.678 写成 544667,这没问题。

但是当使用%.5g时,同样的数字写成5.4467E+5

为什么这里使用指数表示法 (%e) 而 544670 (%f) 比它更短。

谁能帮我理解一下?这是错误吗?

类似地,44.35在使用%.1f时写成44.4,这很好。 但是当使用%.1f时,44.55写成44.5。为什么不写成44.6呢?这是错误吗?

最佳答案

使用最短的表示:%e 或 %f 不够精确。

C11 7.21.6.1 The fprintf function

A double argument representing a floating-point number is converted in style f or e (or in style F or E in the case of a G conversion specifier), depending on the value converted and the precision. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X :

— if P > X ≥ −4, the conversion is with style f (or F) and precision P − (X + 1).

— otherwise, the conversion is with style e (or E) and precision P − 1.

Finally, unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining.

所以在 %.5g544666.678 的例子中,P5,并且 X5,根据规则,使用 e 样式,因为 P > X ≥ −4 为假。

关于c - %g 在 printf 中的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34669026/

相关文章:

c - 了解矩阵 c 的分配

c++ - 如何将一个数字分成几个不等但递增的数字[用于发送 PlaceOrder( OP_BUY,lots ) 合约 XTO ]

iPhone - 获取指向 CGDataProvider 背后数据的指针?

c++ - 使用 BSD 套接字的 HTTP 服务器不关闭连接或与 Windows 浏览器通信

c - send()和recv()给我带来问题

c - 如何在 C 程序中为 setuid 找到用户的 UID?

c++ - 混合语言代码文档 - 需要帮助来调试 doxygen

c - 如何使用 MinGW 和 Sublime Text 3 构建 GLUS

c - Linux DMA : Using the DMAengine for scatter-gather transactions

c - 合并其他 .c 文件时 Makefile 返回错误