c++ - 在 Vector 上 push_back 时设置精度

标签 c++ boost vector tokenize atof

我正在逐行读取 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/

相关文章:

c++ - 检查内存泄漏问题

c++ - Visual Studio 中的 CMake 项目 : How to add additional include and library directories?

c++将 vector 元素写入拆分文件

C++ - 在基于磁盘的 vector 中管理引用

c++ - 在 C++ 中将函数指针中的 const 参数转换为非 const

c++ - 返回字符串 vector 的最简单的 lua 函数

c++ - 带有用 C 编写的库的智能指针

c++ - 如何按插入顺序从 map 中检索元素?

c++ - boost::make_shared<string>() 与 boost::make_shared<string>(string (""))

c++ - 将 pop_front 实现为 std::vector 的快速方法