如何更改 stl 的打印精度?

发布于 2024-08-25 04:57:32 字数 840 浏览 4 评论 0原文

我想使用带有小数位数的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

┈┾☆殇 2024-09-01 04:57:32

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

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

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

 file1 << std::fixed << std::setprecision(precision)
     << thePoint[0]  << "\\"
     << thePoint[1]  << "\\"
     << thePoint[2] << "\\";
魂ガ小子 2024-09-01 04:57:32

尝试

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

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

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

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

Try

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文