当我使用 printf("%.6g\n",36.666666662);
时,我期望输出 36.666667
。但实际输出是36.6667
我给出的格式有什么问题?我的目标是有 6 个小数位
最佳答案
这是正确的行为。根据cplusplus.com :
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point.
For g and G specifiers: This is the maximum number of significant digits to be printed.
如果您使用 f
而不是 g
那么它将按您预期的那样工作。
示例代码
#include <stdio.h>
int main(void) {
printf("%.6g\n", 36.666666662);
printf("%.6f\n", 36.666666662);
return 0;
}
结果
36.6667
36.666667
在线查看它:ideone .
关于c++ - %g 精度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13878369/