【问题标题】:How to change/control the output precision in gcc or g++?如何更改/控制 gcc 或 g++ 中的输出精度?
【发布时间】:2015-01-14 10:26:22
【问题描述】:

我有以下用 c++ 编写并由 g++ 4.8 编译的代码。

double x = 0.123456789;
cout << x << endl;

我不明白为什么我只得到输出

0.1234567

即使我将 x 定义为 long double x。这可能是一个非常幼稚的问题,但是任何人都可以给我一些打击吗?

【问题讨论】:

  • 你试过用谷歌搜索“C++ 输出精度”或类似的东西吗?如果是这样,请告诉我们您发现了什么以及您不了解的地方。
  • 如果你搜索过它,编译器名称可能会使搜索引擎偏离轨道(我的结果在包含“g++”时是无用的)。您的标题“如何在 c++ 中更改/控制输出精度?”的一个不太具体的版本会返回良好的搜索结果。

标签: c++ gcc g++


【解决方案1】:

This page 拥有你所需要的一切,即你应该使用std::setprecision 流操纵器。

double x = 0.123456789;
std::cout << std::setprecision(10) << x << std::endl;

【讨论】:

    【解决方案2】:

    使用precision 函数或setprecision 操纵器来设置有效数字位数(或小数位数,如果您还使用fixed)。

    cout.precision(10);  // 10 significant figures
    

    cout << setprecision(10); // also 10 significant figures
    

    cout << fixed << setprecision(10);  // always fixed-point format, 10 decimal places
    

    默认精度为6。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 2021-08-17
      • 2011-04-25
      • 2018-03-29
      相关资源
      最近更新 更多