【问题标题】:Prevent scientific notation in ostream when using << with double使用带双精度的 << 时防止 ostream 中的科学记数法
【发布时间】:2011-01-21 02:17:39
【问题描述】:

我需要防止我的替身在我的文件中以科学计数法打印,

当我这样做时

outfile << X;

【问题讨论】:

标签: c++ iostream scientific-notation


【解决方案1】:

要设置浮动变量的格式,您可以使用setprecision(n)showpointfixed 的组合。为了使用像 setprecision(n) 这样的参数化流操纵器,您必须包含 iomanip 库:

#include <iomanip>

setprecision(n): 将浮动输出限制到n 位置,一旦设置它,它就会一直设置,直到您为流输出的其余部分显式取消设置。

fixed: 将强制所有浮点数以相同的方式输出。因此,如果您的精度设置为 4 位,6.26.20 都将输出为:

6.2000
6.2000

showpoint: 将强制显示浮点变量的小数部分,即使它没有明确设置。例如,4 将输出为:

4.0

一起使用它们:

outfile << fixed << showpoint;
outfile << setprecision(4);
outfile << x;

【讨论】:

  • 是什么让您认为 showpoint 在这里有什么不同?由于精度原因,小数部分始终显示为 0。
  • 我只需要包含&lt;iomanip&gt; 并使用setprecision(n)
【解决方案2】:

这是一个使用示例 http://cplus.about.com/od/learning1/ss/clessontwo_4.htm

根据你的问题使用

  std::cout << std::fixed << a << std::endl;

【讨论】:

  • 更好的答案,因为它直接回答了问题('固定')。
【解决方案3】:

以上所有答案都很有用,但没有一个能直接回答问题。

outfile.setf(std::ios_base::fixed);
outfile << x;

我在@moogs 链接中找到了答案:http://www.cplusplus.com/reference/iostream/ios_base/fmtflags/

这是一个演示程序:http://ideone.com/FMxRp1

【讨论】:

    【解决方案4】:

    【讨论】:

      猜你喜欢
      • 2022-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2023-03-07
      相关资源
      最近更新 更多