如何在 C++ 中为 float 设置精度

How to set precision for float in C++

我想在 C++ 中为 float 设置精度。假设我的代码是

float a = 23.5, b = 24.36; float c = a + b;

如果我打印这个

cout << c;

它给出: 46.86

但是我想打印到小数点后一位。 怎么做?

您使用 setprecision 指定最小精度。 fixed 将确保小数点后有固定的小数位数。

cout << setprecision (1) << fixed << c;

这个例子可能会帮助您理解。您需要阅读更多有关可能发生的浮点数和舍入错误的信息。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    float a = 3.25;

    cout << fixed << setprecision(1) << a;
}