在整个文件范围内设置 std::cout 的精度 - C++伊奥马尼普

发布于 2024-08-31 06:23:31 字数 395 浏览 1 评论 0原文

我正在做一些计算,结果保存在文件中。我必须输出非常精确的结果,接近双精度变量的精度,为此我使用 iomanip set precision(int) 。问题是我必须将 set precision 放在输出中的任何位置,如下所示:

func1() {
cout<<setprecision(12)<<value;
cout<<setprecision(10)<<value2;
}
func2() {
cout<<setprecision(17)<<value4;
cout<<setprecision(3)<<value42;
}

这非常麻烦。有没有办法更普遍地设置 cout 固定修饰符?

谢谢

I'm doing some calculations, and the results are being save in a file. I have to output very precise results, near the precision of the double variable, and I'm using the iomanip setprecision(int) for that. The problem is that I have to put the setprecision everywhere in the output, like that:

func1() {
cout<<setprecision(12)<<value;
cout<<setprecision(10)<<value2;
}
func2() {
cout<<setprecision(17)<<value4;
cout<<setprecision(3)<<value42;
}

And that is very cumbersome. Is there a way to set more generally the cout fixed modifier?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

累赘 2024-09-07 06:23:31

您是否在寻找 cout. precision

Are you looking for cout.precision ?

请持续率性 2024-09-07 06:23:31

在 C++20 中,您将能够使用 std:: format 默认情况下为您提供最短的十进制表示形式,因此即使您不手动指定它也不会丢失精度。例如:

std::cout << std::format("{}", M_PI);

prints

3.141592653589793

如果您需要固定精度,您可以将其存储在变量中并在多个位置重复使用:

int precision = 10;
std::cout << std::format("{:.{}}", value, precision);

In C++20 you'll be able to use std::format which gives you shortest decimal representation by default, so you won't loose precision even if you don't specify it manually. For example:

std::cout << std::format("{}", M_PI);

prints

3.141592653589793

If you need a fixed precision you can store it in a variable and reuse in multiple places:

int precision = 10;
std::cout << std::format("{:.{}}", value, precision);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文