【问题标题】:How to use setprecision in cpp for only the number of floating points如何在cpp中使用setprecision仅用于浮点数
【发布时间】:2015-04-22 05:07:34
【问题描述】:

当计算一个带浮点数的数字时,即 31.14159,我如何设置 cout 以在浮点上使用 setprecision(4):

cout <<setprecision(4)<< 31.14159<<endl; // returns 31.14

按原样,它考虑整数及其十进制数字,并输出:31.14。但是,我想得到:31.1416。

【问题讨论】:

标签: c++ precision cout iomanip


【解决方案1】:

std::fixed 表示小数点后会有固定的小数位数。

std::cout << std::setprecision(4) << std::fixed << 31.14159;

- 这将打印31.1416

【讨论】:

  • 我试图通过添加 2 个双精度来理解“setprecision”,加法在小数部分有“0”。并且使用 'cout
【解决方案2】:

您可以使用std::fixed

std::cout << std::fixed << std::setprecision(4) << 31.14159 << endl ;

你会得到31.1416的输出

当您添加std::fixed时,std::setprecision(4)将在小数部分生效,因此您将获得小数点后的4值。

std::setprecision() 将对整个号码生效。但是,当您同时添加 std::fixed 时,std::setprecision() 将只影响数字的小数部分。

【讨论】:

  • 我试图通过添加 2 个双精度来理解“setprecision”,加法在小数部分有“0”。并且使用 'cout
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
相关资源
最近更新 更多