[英]C++ stof function cast to integer
#include <iostream>
int main()
{
int val = std::stof("4.99") * 100;
std::cout << val;
return 0;
}
I've tried other strings and they all seem to be converting correctly, but I am not sure what is happening behind the scenes that is causing this to output 498
instead of 499
. 我已经尝试了其他字符串,它们似乎都正确转换,但我不确定幕后发生了什么导致输出498
而不是499
。 In my use case, every string has a maximum of 2
decimal places. 在我的用例中,每个字符串最多包含2
个小数位。
The nearest IEEE754 float
to 4.99
is 4.9899997711181640625
. 最接近 4.99
IEEE754 float
是4.9899997711181640625
。 std::stof
will return the latter. std::stof
将返回后者。
That multiplied by 100
is 498.999969482421875
which is truncated to 498
. 乘以100
是498.999969482421875
,被截断为498
。
This is one of the pitfalls of floating point arithmetic I'm afraid; 这是我害怕的浮点运算的一个陷阱; you need to take a lot of care when using a discontinuous function like a conversion of float
to int
; 使用不连续的函数时需要非常小心,比如将float
转换为int
; using std::lround
on the result would work in your particular case. 在结果上使用std::lround
将适用于您的特定情况。
Further reading: Is floating point math broken? 进一步阅读: 浮点数学是否破裂?
Use a proper function that will round your floating point number properly: 使用适当的函数来正确舍入浮点数:
#include <cmath>
#include <iostream>
int main()
{
auto val = std::lround(std::stof("4.99") * 100);
std::cout << val;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.