代码之家  ›  专栏  ›  技术社区  ›  mmr

如何更改stl打印的精度?

  •  3
  • mmr  · 技术社区  · 14 年前

    所以,如果我这么做:

    int precision = 16;
    std::vector<double> thePoint(3);
    thePoint[0] = 86.3671436;
    thePoint[1] = -334.8866574;
    thePoint[2] = 24.2814;
    ofstream file1(tempFileName, ios::trunc);
    file1 << std::setprecision(precision)
        << thePoint[0]  << "\\"
        << thePoint[1]  << "\\"
        << thePoint[2] << "\\";
    

    我会得到这样的数字:

    86.36714359999999\-334.8866574\24.28140258789063
    

    我想要的是:

    86.37\-334.89\24.28
    

    换句话说,在两个小数点处截断。如果我把精度设为4,那我就得到

    86.37\-334.9\24.28
    

    也就是说,第二个数字被不恰当地截断了。

    2 回复  |  直到 12 年前
        1
  •  7
  •   kumar    14 年前

    使用std::fixed,这应该适合您。

     file1 << std::fixed << std::setprecision(precision)
         << thePoint[0]  << "\\"
         << thePoint[1]  << "\\"
         << thePoint[2] << "\\";
    
        2
  •  2
  •   Jon Reid    14 年前

    file1 << std::setiosflags(ios::fixed) << std::setprecision(precision)
    

    (顺便说一下,这不是 STL iostream .)

    哦!我觉得库马尔比我强 std::fixed .