【问题标题】:How can I change the precision of printing with the stl?如何使用 stl 更改打印精度?
【发布时间】:2010-03-18 04:42:18
【问题描述】:

我想使用带有小数位数的 stl 将数字打印到文件中,而不是整体精度。

所以,如果我这样做:

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

即,第二个数字被不正确地截断。

我不想为了截断而显式操作每个数字,尤其是因为我似乎偶尔会得到 9 重复或 0000000001 或类似的东西。

我确信有一些明显的东西,比如使用 printf(%.2f) 或类似的东西,但我不确定如何将它与 stl

【问题讨论】:

    标签: c++ precision iostream


    【解决方案1】:

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

     file1 << std::fixed << std::setprecision(precision)
         << thePoint[0]  << "\\"
         << thePoint[1]  << "\\"
         << thePoint[2] << "\\";
    

    【讨论】:

      【解决方案2】:

      试试

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

      设置定点格式而不是浮点数。

      (顺便说一句,这不是STL。这是iostream。)

      ……哦!我认为 Kumar 用std::fixed 比我更好。

      【讨论】:

      • 仅仅因为某些东西使用了模板并不能使其成为 STL。点击链接,您会发现它们完全不同。
      猜你喜欢
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多