c++ - 处理 float 不准确

标签 c++ precision floating-accuracy floating-point-conversion

我有一个字符串

strValue = "11.900000"

我想将其解析为浮点值。所以我尝试了:

float fValue = -1;
sscanf_s(strValue.c_str(), "%f", &fValue);

try
{
    double test = std::stod(strValue, &sz);
    fValue = (float) std::stod(strValue, &sz);
}
catch (...)
{
    fValue = -1;
}

对于 double 它是准确的:

test = 11.900000000000000

float 是不准确的:

fValue = 11.8999996

有没有可能准确地做到这一点? (我知道使用 float 会不准确,但有更好的方法吗?)

最佳答案

11.899999611.9 的最精确近似值,可以用 float 类型表示。

关于c++ - 处理 float 不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30974519/

相关文章:

postgresql - Postgresql 中 PostGis 中的 double

erlang - Erlang 中的精度

javascript - float 显示错误

prolog - lib(ic) 的精确解

floating-point - 浮点不准确示例

c++ - 重载函数以获取 true_type 或 false_type 参数与使用 if 检查?

c++ - 外部变量是否初始化为其默认值?

c++ - 如何将小数点分隔符设置为逗号?

r - 为什么这些数字不相等?

C++计算平均值和标准差