5

我一直在研究一个问题,我将浮点数转换为人类可读的格式,然后再返回。即一个字符串。我在使用 stringstream 时遇到了问题,发现 atof 产生“更好”的结果。

注意,在这种情况下我没有打印出数据,我使用调试器来检索值:

    const char *val = "73.31";
    std::stringstream ss;
    ss << val << '\0';
    float floatVal = 0.0f;
    ss >> floatVal; //VALUE IS 73.3100052

    floatVal = atof(val); //VALUE IS 73.3099976

对此可能有一个合理的解释。如果有人能启发我,我会很感激:)。

4

1 回答 1

2

答案基于 OP 使用 MSVC 的假设

atof在读取浮点值方面确实比istream.

看这个例子:

#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdlib>

int main()
{
    const char *val = "73.31";
    std::stringstream ss;
    ss << val;
    float floatVal = 0.0f;
    ss >> floatVal;
    std::cout << "istream>>(float&)                       :" << std::setw(18) << std::setprecision(15) << floatVal << std::endl;

    double doubleVal = atof(val);
    std::cout << "double atof(const char*)                :" << std::setw(18) << std::setprecision(15) << doubleVal << std::endl;

    floatVal = doubleVal;
    std::cout << "(float)double atof(const char*)         :" << std::setw(18) << std::setprecision(15) << floatVal << std::endl;

    doubleVal = floatVal;
    std::cout << "(double)(float)double atof(const char*) :" << std::setw(18) << std::setprecision(15) << floatVal << std::endl;
}

输出:

istream>>(float&)                       :  73.3100051879883
double atof(const char*)                :             73.31
(float)double atof(const char*)         :  73.3099975585938
(double)(float)double atof(const char*) :  73.3099975585938

编译器甚至警告从doublefloat这个的转换:

warning C4244: '=': conversion from 'double' to 'float', possible loss of data

我还找到了这个页面:浮点类型的转换


更新:

value73.3099975585938似乎是对value的正确float解释。double73.31


更新: istream>>(double&)也可以正常工作:

#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdlib>

int main()
{
    const char *val = "73.31";
    std::stringstream ss;
    ss << val;
    double doubleVal = 0.0f;
    ss >> doubleVal;
    std::cout << "istream>>(double&) :" << std::setw(18) << std::setprecision(15) << doubleVal << std::endl;
}

输出:

istream>>(double&) :             73.31

对于算术类型istream::operator>>使用num_get::get. num_get::get应该使用类似scanf("%g")for float source

但:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>


int main()
{
    std::string s = "73.31";
    float f = 0.f;
    sscanf(s.c_str(), "%g", &f);
    std::cout << std::setw(18) << std::setprecision(15) << f << std::endl;
}

输出:

73.3099975585938

对我来说,这看起来微软可能存在错误num_get

于 2015-09-10T07:54:13.230 回答