📜  如何在 C++ 中格式化小数点(1)

📅  最后修改于: 2023-12-03 15:24:08.373000             🧑  作者: Mango

如何在C++中格式化小数点

在C++中,格式化小数点可以使用 iomanip 库中的 setprecision() 函数,该函数允许您指定小数点后的位数。

以下是如何使用 setprecision() 函数来格式化小数点的示例程序:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double number = 3.14159265358979323846;

    cout << "Number with default precision: " << number << endl;

    cout << fixed << setprecision(2) << "Number with precision 2: " << number << endl;

    cout << fixed << setprecision(5) << "Number with precision 5: " << number << endl;

    return 0;
}

输出:

Number with default precision: 3.14159
Number with precision 2: 3.14
Number with precision 5: 3.14159

如上所述,我们可以使用 setprecision() 函数来设置输出流的精度。 setprecision() 函数设置小数点后的位数,通过 fixed 操纵符将浮点数格式化为定点表示。

还有一些其他的格式化选项可以在iomanip库中使用,这里只是一个简单的样例。