我正在逐行读取 CSV,并对每个逗号分隔值进行标记。每个标记都是字符串类型。我将它放入一个浮点类型的 vector 中。在下面的示例中,例如,如果 csv 中的值为 "0.08",*beg = "0.08",但在 vector v 中为 "0.079999998"
有什么方法可以将 vector 的精度设置为小数点后 3 位或其他。
例子:
string line;
boost::char_separator<char> sep(",");
typedef boost::tokenizer< boost::char_separator<char> > t_tokenizer;
ifstream myfile (fileName);
if(myfile.is_open())
{
while (myfile.good())
{
getline (myfile,line);
t_tokenizer tok(line, sep);
for (t_tokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg)
{
string temp = *beg;
this->v.push_back(::atof(temp.c_str()));
}
最佳答案
这不是 float 的问题。您不能准确表示 0.8,但不用担心 - 只需输出具有所需精度的值即可:
#include <iomanip> // for fixed and setprecision
#include <iostream> // for cout
#include <cstdio> // for printf
for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
{
std::cout << std::fixed << std::setprecision(3) << *it << std::endl;
}
或者,您可以使用 std::printf("%.3f\n", *it)
。
如果您真的想在数据结构中存储精确 值,则不能使用普通 float 。您可以使用某种整数的定点解释(例如,以 1/1000 为单位测量所有内容),或者您可以使用十进制 float (很少见),或者您可以存储有理数数字(商整数)。如果您只做加法和减法,定点将是自然的选择。
关于c++ - 在 Vector 上 push_back 时设置精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8205215/