如何更改 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
ie,第二个数字被不正确地截断。
我不想显式地操作每个数字来获得截断,特别是因为我似乎偶尔会得到重复的 9 或 0000000001 或类似的东西。
我确信有一些明显的东西,比如使用 printf(%.2f) 或类似的东西,但我不确定如何将其与 stl << 混合使用。和外流。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 std::fixed ,这应该适合你。
Use std::fixed , this should work for you.
尝试
设置定点格式而不是浮点。
(顺便说一下,这不是 STL。它是 iostream。)
……哦!我认为 Kumar 的
std::fixed
比我更好。Try
which sets fixed-point format instead of floating-point.
(By the way, this is not STL. It's iostream.)
…Oh! I think Kumar bettered me with
std::fixed
.