简体   繁体   English

为什么printf(“%。6g,<value>)在小数点后忽略零?

[英]Why does printf("%.6g, <value>) ignore zeroes after decimal point?

I want to print maximum of 6 digits after the decimal point, so I used the following: 我想在小数点后打印最多6位数,所以我使用了以下内容:

printf("%.6g",0.127943989);

the output of printf is 0.127944 which is correct, but when I tried this: printf的输出是0.127944这是正确的,但当我尝试这个:

printf("%.6g",0.007943989);

the output became 0.00794399 which is not what I expected to see! 输出变为0.00794399,这不是我期望看到的!

It seems that printf ignores zeros after the decimal point. 似乎printf在小数点后忽略零。 So how can I force it to output maximum of 6 digit precision? 那么如何强制它输出最大6位精度?

Is the "%f" format specifier: "%f"格式说明符:

printf("%.6f\n",0.007943989)  // prints 0.007944

what you're looking for? 你在找什么? Keep in mind that this won't automatically switch over to the %e format style if the number warrants it, so this might not be exactly what you're looking for either. 请记住,如果数字保证,它不会自动切换到%e格式样式,因此这可能不是您正在寻找的。

For example, the following: 例如,以下内容:

printf("%.6g\n",0.00007943989);
printf("%.6f\n",0.00007943989);

prints: 打印:

7.94399e-005
0.000079

and it's not clear if you want the exponential form for the smaller numbers that "%g" provides. 并且不清楚你是否想要"%g"提供的较小数字的指数形式。

Note that the spec for %f and %g has a slightly different behavior for how the precision specification is handled. 请注意, %f%g的规范对于如何处理精度规范的行为略有不同。

  • for %f : "the number of digits after the decimal-point character is equal to the precision specification" for %f :“小数点字符后的位数等于精度规格”
  • for %g : "with the precision specifying the number of significant digits" for %g :“精度指定有效位数”

And that the run of zeros after the decimal point do not count toward significant digits (which exlpains the behavior you see for %g ). 并且小数点后的零运行不计入有效数字(这表示你看到%g的行为)。

The ISO C standard requires that ISO C标准要求

An optional precision, in the form of a period ('.') followed by an optional decimal digit string... This gives ... the maximum number of significant digits for g and G conversions 一个可选的精度,以句点('。')的形式,后跟一个可选的十进制数字字符串......这给出了... gG转换的最大有效位数

Here is the output that you would get with GNU libc (GCC 4.5.1, libc 2.11; GCC 4.6.3, libc 2.15) 以下是使用GNU libc获得的输出(GCC 4.5.1,libc 2.11; GCC 4.6.3,libc 2.15)

printf("%.6g\n", 0.12);
0.12
printf("%.6g\n", 0.1234567890);
0.123457
printf("%.6g\n", 0.001234567890);
0.00123457
printf("%#.6g\n", 0.001234567890);
0.00123457
printf("%.6g\n", 0.00001234567890);
1.23457e-05
printf("%#.6g\n", 0.00001234567890);
1.23457e-05

printf("%.6f\n", 0.12);
0.120000
printf("%.6f\n", 0.1234567890);
0.123457
printf("%.6f\n", 0.001234567890);
0.001235
printf("%#.6f\n", 0.001234567890);
0.001235
printf("%.6f\n", 0.001234567890);
0.000012
printf("%#.6f\n", 0.001234567890);
0.000012

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM