Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange! linux & windows vsprintf float num to file

use vsprintf to write the content to file.

output format is:

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

linux:

gcc 4.4.5: -O2 -ffloat-store

In linux.in file is like this:

tt2:30759.257812, tt2:46f04e84

windows:

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

In windows. in file is like this:

tt2:30759.257813, tt2:46f04e84

Why that is different?

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

I have find the reason for my case.

In windows, I use the ofstream to output to file. It'c c++ lib.

In linux, I just use write to output to file. It's c lib.

When I use ofstream in linux, the output is the same.

After all, thanks for everyone~

like image 684
hdbean Avatar asked Jul 08 '26 18:07

hdbean


1 Answers

Floating-point numbers are stored in the computer in binary. When printing them into decimal floating-point, there are multiple correct representations for them. In your case, both of them are correct, as both of them convert back to the original binary floating-point value. Look at the output of this file, which I compiled using 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);
}

Output:

46f04e84
46f04e84

Therefore, an implementation of printf and friends may choose to display any of the two decimal floating-point numbers.

like image 105
user1202136 Avatar answered Jul 11 '26 12:07

user1202136