C/C++ 下完全复刻 Python print(“%s”, floatnum) 好像有点难

25次阅读

共计 560 个字符,预计需要花费 2 分钟才能阅读完成。

$ cat test.c
#include 

void main()
{
    double v = 1.38;
    printf("%lfn", v);
    printf("%.17gn", v);
}

$ gcc test.c -o test
$ ./test
1.380000
1.3799999999999999

$ python3
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> v = 1.38
>>> print("%s" % v)
1.38

需求很简单:我要在 C/C++ 中打印浮点数时,像 Python “%s” % v 那样打印,只打印必要的小数点后内容

Stack Overflow 上有一篇讨论

https://stackoverflow.com/questions/16839658/printf-width-specifier-to-maintain-precision-of-floating-point-value

建议使用 printf(“%.17g”, number) 但是测试后发现它不工作

简单翻了一些资料,似乎 %.17g 的数字要达到 17 确实是有必要的

(我的系统是 Ubuntu 22.04 / x86_64)

正文完
 0