gpt4 book ai didi

c - printf 的浮点值 10.1 的意外输出

转载 作者:行者123 更新时间:2023-11-30 17:49:11 25 4
gpt4 key购买 nike

谁能解释一下 %g 和 %f 之间的区别吗?我知道 %0.2f 因为我理解它只在点后 2 位小数打印!我尝试了这段代码...

int main()
{
float val = 10.0;
printf("<%g><%0.2g><%0.4g><%f><%0.2f>", val, val, val, val, val);

return 0;
}
//giving : <10><10><10><10.000000><10.00>

//If i give 10.1 instead!
int main()
{
float val = 10.1;
printf("<%g><%0.2g><%0.4g><%f><%0.2f>", val, val, val, val, val);

return 0;
}
//giving : <10.1><10><10.1><10.000000><10.00>
// How come here i got for %g --> 10.1
// %0.2g --> 10
// %0.4g --> 10.1

请有人澄清我!

最佳答案

%g%G 的 Linux 程序员手册:

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.

因此,在 .是字段宽度;后 。是结果中有效数字的最大数量,但尾随零将被删除。具有 4 位有效数字的 10.10000 是 10.10,但删除尾随零的结果是 10.1。保留 2 位有效数字后,结果为 10。%g 等于 %.6g

但是请注意第二部分:

Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision.

这意味着使用 %0.2g 格式化的 100 会产生 1e+02

关于c - printf 的浮点值 10.1 的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18034829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com