gpt4 book ai didi

c - 为什么我在 linux 和 OS/X 上得到不同的输出

转载 作者:IT王子 更新时间:2023-10-29 00:44:15 26 4
gpt4 key购买 nike

我正在尝试一个非常简单的 printf 测试:

printf "%.16f\n" 5.10

在 Linux 上,我得到了这个输出:5.100000000000000000,这是预期的。

但是在 OS/X 上进行的完全相同的测试产生了这个:5.0999999999999996

为什么 printf 产生不同的输出?

编辑:这不是 C 代码,printf 也是一个命令行实用程序,方便脚本和测试。

下面等效的 C 程序生成 5.100000000000000000:

#include <stdio.h>

int main() {
printf("%.16f\n", 5.10);
return 0;
}

编辑 2:情节变浓了……为了让 linux 用户更感兴趣,如果我以 nobody 身份运行此命令,我会得到与操作系统/X:

chqrlie$ printf "%.18f\n" 5.10
5.100000000000000000
chqrlie$ su nobody -c 'printf "%.18f\n" 5.10'
5.099999999999999645

最佳答案

printf 的 GNU 实现和 MacOS (FreeBSD) 实现都是不同的程序。两者都旨在与 POSIX 标准兼容。

POSIX 将 float 的表示留给 printf 的实现。他们的论点是 shell 中的所有计算无论如何都是整数。

The floating-point formatting conversion specifications of printf() are not required because all arithmetic in the shell is integer arithmetic. The awk utility performs floating-point calculations and provides its own printf function. The bc utility can perform arbitrary-precision floating-point arithmetic, but does not provide extensive formatting capabilities. (This printf utility cannot really be used to format bc output; it does not support arbitrary precision.) Implementations are encouraged to support the floating-point conversions as an extension.

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html


附言:

5.1

不是 bash 中的 float 。 bash 不支持 float 。

5.1 是一个字符串,由 printf 根据语言环境(!)解释

theymann@theymann-laptop:~/src/sre/inventory-schema$ LANG=en_US.UTF8 printf "%.16f\n" 5.10
5.1000000000000000
theymann@theymann-laptop:~/src/sre/inventory-schema$ LANG=de_DE.UTF8 printf "%.16f\n" 5.10
bash: printf: 5.10: Ungültige Zahl. # << German: Bad Number
0,0000000000000000

注意:在德国,我们使用 , 作为小数点分隔符。


普通用户和没有人必须使用的 shell 之间的输出差异。一些 shell,比如 busybox 带有它们自己的 printf 实现。顺便说一句,我非常惊讶没有人被允许在您的系统上执行命令!

关于c - 为什么我在 linux 和 OS/X 上得到不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55646882/

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