如何使用stl更改打印的精度? [英] How can I change the precision of printing with the stl?

查看:537
本文介绍了如何使用stl更改打印的精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用带有小数位数的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< and ofstream。

解决方案

使用std :: fixed可以为你工作。

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


I want to print numbers to a file using the stl with the number of decimal places, rather than overall precision.

So, if I do this:

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] << "\\";

I'll get numbers like this:

86.36714359999999\-334.8866574\24.28140258789063

What I want is this:

86.37\-334.89\24.28

In other words, truncating at two decimal points. If I set precision to be 4, then I'll get

86.37\-334.9\24.28

ie, the second number is improperly truncated.

I do not want to have to manipulate each number explicitly to get the truncation, especially because I seem to be getting the occasional 9 repeating or 0000000001 or something like that that's left behind.

I'm sure there's something obvious, like using the printf(%.2f) or something like that, but I'm unsure how to mix that with the stl << and ofstream.

解决方案

Use std::fixed , this should work for you.

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

这篇关于如何使用stl更改打印的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆