%g 如何对浮点数进行四舍五入?

发布于 2024-09-25 20:58:48 字数 200 浏览 13 评论 0原文

当我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

能否归途做我良人 2024-10-02 20:58:48

%g 格式说明符的舍入方式与 %f 类似,但如果 %f 会产生 4.234000,则 %g 将省略尾随零并打印 4.234

当某些数字打印为 12345.6,而稍大的数字将打印为 1.235 时,应使用 %g e04

The %g format specifier does its rounding just like %f would do, but if %f would result in 4.234000, then %g will omit the trailing zeros and print 4.234.

%g should be used when it makes the most sense in your output format that some numbers are printed as 12345.6, while a slightly bigger number would be printed as 1.235e04.

☆獨立☆ 2024-10-02 20:58:48

%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.

是你 2024-10-02 20:58:48

对于 %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.

酒浓于脸红 2024-10-02 20:58:48

来自 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文