c++ - atof() 返回 float 而不是 double

标签 c++ string double atof

我的文本文件包含精确到小数点后 12 位的数字。

所以为了将数字加载到 c++ vec 中,我写了这个

void txt2vec(const std::string& file, std::vector<double>& data)
{
std::string line;
std::ifstream myfile(file);
if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {

        std::cout << atof(line.c_str()) << std::endl;
        //data.push_back(atof(line.c_str()));
    }
    myfile.close();
}
}

atof 应该返回一个 double 但我得到了 float

这是程序的输出

 -0.0340206
 -0.0873645
  0.0789533
  0.115022
  0.0809852
  0.118469
  0.113328
  0.112746
 -0.0331071

它应该在哪里

  -0.0340205617249
  -0.0873644948006
   0.078953281045
   0.115022487938
   0.0809852406383
   0.118468873203
   0.11332821846
   0.112745501101
  -0.0331071354449

最佳答案

您可能会得到预期的值,但您没有在显示的代码中打印出完整的精度。

<<输出流和 double 运算符的默认精度为 6,用于一般用途和可读性。参见 std::ios_base::precision .

The default precision, as established by std::basic_ios::init, is 6.

如果你想显示完整的数字,你需要用 double 可能包含的位数来设置精度,例如使用 numeric_limits .

std::cout << -0.0340205617249 << std::endl; // -0.0340206
std::cout.precision(std::numeric_limits<double>::digits10 + 1);
std::cout << -0.0340205617249 << std::endl; // -0.0340205617249

另见 std::setprecision .

关于c++ - atof() 返回 float 而不是 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45865109/

相关文章:

c - 合并排序 C 中的字符串数组

c - 从 memcpy 返回到双变量

c++ - 涉及函数类型的表达式是左值还是右值?

C++:使用 pthread_create 创建新线程,以运行类成员函数

c++ - 多屏系统C中的鼠标光标位置

JavaScript - 有没有办法检查字符串是否包含关键字但仅包含该关键字?

c++ - 为什么我的质量计算器不能正确处理空格?

c - 在 char[] 缓冲区中保存 double 值

C++打印出 vector 的位集<unsigned char>

c++ - 当使用shared_ptr创建实例时,指针实例变量会发生什么情况?