c++ - 奇怪的! linux 和 windows sprintf float 到文件

标签 c++ windows linux floating-point printf

使用 vsprintf 将内容写入文件。

输出格式为:

"tt2:%f, tt2:%x", tt2, *((int *)&tt2)

Linux:

gcc 4.4.5: -O2 -ffloat-store

在linux.in文件中是这样的:

tt2:30759.257812, tt2:46f04e84

window :

vs2005 sp1: /O2 Precise (/fp:precise)

在窗口中。在文件中是这样的:

tt2:30759.257813, tt2:46f04e84

为什么不一样?

==================================

我找到了我的案子的原因。

在 Windows 中,我使用 ofstream 输出到文件。它是 C++ 库。

在 linux 中,我只是使用 write 来输出到文件。它是 c 库。

当我在 linux 中使用 ofstream 时,输出是相同的。

总之还是谢谢大家~

最佳答案

float 以二进制形式存储在计算机中。当将它们打印成十进制 float 时,它们有多种正确的表示形式。在您的情况下,它们都是正确的,因为它们都转换回原始二进制浮点值。查看我使用 GCC 编译的这个文件的输出:

#include <stdint.h>
#include <stdio.h>

int main()
{
    float a = 30759.257812f;
    float b = 30759.257813f;

    printf("%x\n%x\n", *(uint32_t *)&a, *(uint32_t *)&b);
}

输出:

46f04e84
46f04e84

因此,printf 的实现和 friend 们可以选择显示两位十进制 float 中的任何一个。

关于c++ - 奇怪的! linux 和 windows sprintf float 到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12313982/

相关文章:

c++ - 我可以使用 boost::bind 来存储不相关的对象吗?

Windows Azure Node.js SDK

javascript - 如何使用javascript自动关闭网页?

linux - 如何永久清除 linux/ubuntu 终端或 bash 中的所有历史记录?

linux - Apache 不会监听除端口 80 以外的其他端口

C++使用迭代器将函数映射到可迭代对象上

c++ - 在 Windows 上编译的控制台应用程序是否可以在使用 DOSBox 的 Linux 和 MAC OS X 上运行?

c++ - boost::random 每次生成相同的数字

linux - 是否有与 Linux 中的 windows GetSystemTimes() 函数等效的函数?

c++ - 找不到 Magick++ 头文件