%g 如何对浮点数进行四舍五入?
当我在 printf()
中使用 %g
作为格式说明符时,有时它会向上舍入到小数点后 2 位,有时向上舍入到 3 位,有时向上舍入到 4 位。 ..它是如何做到的?
实际上,对于浮点数,我们应该在哪里使用 %g
而不是 %f
或 %e
呢?
While I'm using %g
as format specifier in printf()
, sometimes it rounds up upto 2 places after decimal point, sometimes upto 3 places , someimes upto 4 places...how it does so?
Actually where we should use %g
instead of %f
or %e
for floating point numbers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
%g
格式说明符的舍入方式与%f
类似,但如果%f
会产生4.234000
,则%g
将省略尾随零并打印4.234
。当某些数字打印为
12345.6
,而稍大的数字将打印为1.235 时,应使用
。%g
e04The
%g
format specifier does its rounding just like%f
would do, but if%f
would result in4.234000
, then%g
will omit the trailing zeros and print4.234
.%g
should be used when it makes the most sense in your output format that some numbers are printed as12345.6
, while a slightly bigger number would be printed as1.235e04
.%g
根据值自动在使用%e
和%f
之间“翻转”,以尝试显示尽可能多的信息,与手持计算器的操作方式相同。此外,
%g
不包括尾随零和小数点。%g
automatically 'flips' between using%e
and%f
depending on the value, in an attempt to display as much information as possible, in the same way as hand-held calculators do.Also, with
%g
trailing zeroes and decimal point are not included.对于
%f
转换,“精度”是小数点后的位数,而对于%g
则是小数点后的位数。 有效数字。两种情况下的默认精度均为 6。
For the
%f
conversion, the “precision” is the number of digits after the decimal point, while for%g
it is the number of significant digits.The default precision is 6 in both cases.
来自 printf 手册:
“双参数以 f 或 e(或 F或 E 代表
G 转换)。精度指定有效位数。如果精度缺失,则给出6位;
如果精度为零,则视为1。使用样式e
如果转换后的指数小于 -4 或更大
大于或等于精度。尾随零被删除
结果的小数部分;只出现小数点
如果它后面至少跟着一位数字。”
我的意思不是“RTFM”,但您可能会在手册中有关控制精度和长度的部分中找到所需的内容。
From the printf manual:
"The double argument is converted in style f or e (or F or E for
G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given;
if the precision is zero, it is treated as 1. Style e is used
if the exponent from its conversion is less than -4 or greater
than or equal to the precision. Trailing zeros are removed from
the fractional part of the result; a decimal point appears only
if it is followed by at least one digit."
I don't mean to "RTFM", but you'll probably find what you're looking for in the manual sections on controlling precision and length.