详解setprecision函数

发布时间:2023-05-21

一、setw函数

在介绍setprecision函数前,我们先来了解一下setw函数。 setw函数的作用是设置输出流中下一个输出值所占的宽度,若输出值的数据位数小于设置的宽度,则用空格字符进行左对齐或右对齐操作。

#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
    cout << setw(10) << 123 << endl;
    cout << setw(10) << "Hallo" << endl;
    return 0;
}

上述代码的输出结果为:

       123
     Hallo

二、setprecision函数

setprecision函数的作用是设置数字浮点输出的精度。 通过控制输出流格式控制控制,让输出数据精度达到要求。 setprecision函数可以精确到小数点后面多少位。

#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
    double d1 = 1.234, d2 = 1.235, d3 = 1.236;
    cout << setprecision(1) << d1 << endl;
    cout << setprecision(2) << d2 << endl;
    cout << setprecision(3) << d3 << endl;
    return 0;
}

上述代码的输出结果为:

1.2
1.24
1.236

三、setiosflags函数

setiosflags函数可以设置输出流的一些状态标志。 在使用setiosflags函数时,需要在头文件iomanip中引入setiosflags头文件。 如下:

#include<iomanip>
//头文件iomanip中提供的函数之一

setiosflags函数有许多参数,常见的有:

  • ios::left:向左对齐
  • ios::right:向右对齐
  • ios::showpoint:显示小数点
  • ios::showpos:显示正负号
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
    double d = 12.3456;
    cout << setiosflags(ios::left)
        << setiosflags(ios::showpoint)
        << setiosflags(ios::showpos)
        << setiosflags(ios::fixed)
        << setprecision(3)
        << d << endl;
    return 0;
}

上述代码的输出结果为:

+12.346

四、setbase函数

setbase函数用于设置流使用的输出进制,可以使用16进制、10进制和8进制

#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
    int num = 7;
    cout << setbase(10) << num << endl; //十进制
    cout << setbase(8) << num << endl; //八进制
    cout << setbase(16) << num << endl; //十六进制
    return 0;
}

上述代码的输出结果为:

7
7
7

五、setfill函数

setfill函数用于设置填充字符,可以是空格、0或其他字符。 如下:

#include <iomanip>
//头文件iomanip中提供的函数之一
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
    int num = 7;
    cout << setiosflags(ios::left) << setfill('*') << setw(10) << num << endl;
    cout << setiosflags(ios::right) << setfill('#') << setw(10) << num << endl;//右对齐
    return 0;
}

上述代码的输出结果为:

7********
########7

六、相关函数的综合使用

结合以上函数,可以实现各种复杂的格式控制与输出。

#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
    double d1 = 12341.2312, d2 = 23.1234, d3 = 123143.1234;
    cout << setiosflags(ios::left) << setfill('*') << setw(15) << setprecision(2) << d1 << endl;
    cout << setiosflags(ios::right) << setfill('0') << setiosflags(ios::showpoint) << setw(10) << setprecision(3) << d2 << endl;
    cout << setiosflags(ios::left) << setfill('.') << setw(15) << setprecision(3) << d3 << endl;
    return 0;
}

上述代码的输出结果为:

12341.23*******
000023.123
123143.123......

七、总结

以上就是setprecision函数的相关介绍,结合其他相关函数的使用可以灵活地控制输出格式和数据精度。