为什么字符串到浮点的转换可能不起作用?
在我的 C++ 代码中,我有字符串:“0.55”。
我想将其转换为浮点值“0.55”,但我使用的所有函数都给出浮点值“0.55000001”。
为什么?我怎样才能得到明确的价值?
最后版本的代码是:
wstring s = L"0.55";
float f = stof(s);
Possible Duplicate:
Precision of Floating Point
Can you compare floating point values exactly to zero?
floating point issue
In my c++ code I have the string: "0.55".
And I want to convert it to float value "0.55", but all function I used give me the float value "0.55000001".
Why? How can I take the clear value?
Last version of code is:
wstring s = L"0.55";
float f = stof(s);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
浮动并不精确。这是因为可能的值有无限多个,但表示它们的位数却有限!
因此,由于无法表示
0.55
,因此它会为您提供值0.55000001
。更多信息可以在:每个程序员都应该了解的内容中找到浮点运算
Floats are not exact. This is because there are infinite number of possible values, but only finite number of bits to represent them!
So because
0.55
cannot be represented, it gives you the value0.55000001
instead.More info can be found in: what every programmer should know about floating points arithmetics
0.55
没有精确的二进制表示。总会有一些舍入误差。0.55
does not have an exact binary representation. There will always be some rounding errors.没有浮点值 0.55 - 该格式无法表示该值。
请阅读浮点指南以获取详细说明。
如果您需要小数分数的精确表示,请使用小数格式,例如 GMP 库 提供的格式。
There is no float value 0.55 - the format cannot represent that value.
Read the Floating-Point Guide for a detailed explanation.
If you need an exact representation for decimal fractions, use a decimal format, such as provided by the GMP library.
你可以使用一点代数,你会得到 0.55
wstring s = L“0.55”;
浮动 f = stof(s);
you can use a little algebra and you will get 0.55
wstring s = L"0.55";
float f = stof(s);