【问题标题】:How to write 2 digits after decimal point in C++? [duplicate]如何在 C++ 中写小数点后 2 位数字? [复制]
【发布时间】:2014-01-15 02:55:11
【问题描述】:

在C语言中我们可以这样写;

printf("%.2f", number);

如何在 C++ 中做到这一点?

std::cout << "The number is " << number;

【问题讨论】:

标签: c++ c floating-point double


【解决方案1】:

您需要使用iomanip 的东西,例如:

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.141592653589;
    std::cout << std::fixed << std::setprecision(2) << pi << '\n';
    return 0;
}

哪个输出:

3.14

如果您想本地化更改的效果(fixedsetprecision 都永久更改流),您可以事先保存标志和精度,然后再恢复它们:

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.141592653589;

    std::cout << pi << '\n';

    // Save flags/precision.
    std::ios_base::fmtflags oldflags = std::cout.flags();
    std::streamsize oldprecision = std::cout.precision();

    std::cout << std::fixed << std::setprecision(2) << pi << '\n';
    std::cout << pi << '\n';

    // Restore flags/precision.
    std::cout.flags (oldflags);
    std::cout.precision (oldprecision);

    std::cout << pi << '\n';

    return 0;
}

输出是:

3.14159
3.14
3.14
3.14159

表示正在恢复之前的行为。

【讨论】:

  • 有一点需要注意:std::setprecision(2) 会更改 std::cout 的状态,因此它会影响您以后打印的任何浮点值。
  • @Keith,说得好。虽然它可能不一定直接适用于这个问题,但我会提到它并提供一种解决方法。
猜你喜欢
  • 2012-10-28
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多