我正在尝试修改一些库,我需要在ptree中存储浮动值。然而,当我检索这个价值时,它与我放入那里的不同。这不会发生双打。示例:

Ptree pt;

float f = 230518.391;
pt.put("float", f);
pt.put("double", (double) f)

cout << "f: " << f;
cout << "pt.float: " << pt.get<float>("float");
cout << "pt.double: " << pt.get<double>("double");
.

输出: F:230518.391. pt.float:230518.406. pt.double:230518.391

这里发生了什么?

有帮助吗?

解决方案

Probably a combination of rounding "errors" & the compiler optimizing.. The rounding happens when the float is stored into the property tree..

However when you store a double the rounding doesn't happen. Now at the line pt.put("double", (double) f) the compiler might optimize the "f" away, and put the literal there. So the compiler doesn't use the rounded value. Similar for the first cout cout << "f: " << f; Here too the float is optimized away and the literal is put in its place.

EDIT: just tested it, can it be that the "rounded" value actually is "230518.906

this site might help with converting those numbers :).

其他提示

You need to consider that float as a precision limited to somewhat around 7 digits. Therefore what you are seeing might be the nearest storable float value for your literal. In that case the other outputs might be influenced by compiler optimizations to get you the correct value (the compiler could omit converting f to double and simply put the literal in place.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top