C++指定精度的使用(进制、小数点后位数、域宽、对齐、填充方式)

①输出八进制、十进制、十六进制数据

#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, const char * argv[]) {
    
    
//    ①输出八进制、十进制、十六进制数据
    int a =10;
    cout<<"oct:"<<oct<<a<<endl;    //以八进制输出
    cout<<"dec:"<<dec<<a<<endl;    //以十进制输出
    cout<<"hex:"<<hex<<a<<endl;    //以十六进制输出
    return 0;
}

在这里插入图片描述
在变量前面加oct表示以八进制输出该值
在变量前面加dec表示以十进制输出该值
在变量前面加hex表示以十六进制输出该值

②输出指定精度数据

#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, const char * argv[]) {
    
    
    //    ②输出指定精度数据
    double f = 3.1415926;
    cout<<"默认输出 :"<<f<<endl;
    cout<<"精度控制7位小数"<<setprecision(7)<<setiosflags(ios::fixed)<<f<<endl;
    cout<<"精度控制2位小数"<<setprecision(2)<<setiosflags(ios::fixed)<<f<<endl;
    return 0;
}

在这里插入图片描述
C++中默认输出小数点后5位数

③输出指定域宽、对齐、填充方式的数据

#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, const char * argv[]) {
    
    
//    ③输出指定域宽、对齐、填充方式的数据
    cout<<setw(10)<<3.1415<<endl;
    cout<<setw(10)<<setfill('0')<<3.1415<<endl;
    cout<<setw(10)<<setfill('0')<<setiosflags(ios::left)<<3.1415<<endl;
    cout<<setw(10)<<setfill('-')<<setiosflags(ios::right)<<3.1415<<endl;
    return 0;
}

在这里插入图片描述
setw()中的参数用于指定域宽,对于输出的值没有达到指定域宽的宽度,默认在左侧用空格补齐。

setfill()中的参数用于指定填充的方式,因为默认填充的是空格,所以可以指定自定义的填充方式,参数中的值需要使用单引号 ’ ’ 括起来。

setiosflags()中的参数用于指定对齐方式,也就是指明填充的方向(数据的左边或者右边)。
参数为ios::left时表示左对齐,也就是在数据的右侧进行填充
参数为ios::right时表示右对齐,也就是在数据的左侧进行填充
不设置对齐方式时则默认右对齐进行填充。

猜你喜欢

转载自blog.csdn.net/qq_45696288/article/details/125197086