我的文本文件包含精确到小数点后 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/