C6.【C++ Cont】cout的格式输出

目录

1.头文件

2.使用

1.控制宽度和填充

[setw函数(全称set field width设置字段宽度)](#setw函数(全称set field width设置字段宽度))

[setfill函数(全称Set fill character设置填充字符)](#setfill函数(全称Set fill character设置填充字符))

2.控制数值格式

3.控制整数格式

4.控制对齐方式


1.头文件

用cout进行格式化输出前,先引用头文件iomanip(全称i nput&o utput manipulators)

cpp 复制代码
#include <iomanip>

2.使用

1.控制宽度和填充

setw函数(全称set field width设置字段宽度)

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout<<setw(5)<<a<<endl;
    return 0;
}

可见是右对齐

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout<<a<<setw(5)<<"x"<<endl;
    return 0;
}

在12的右侧,将x右对齐5格

setfill函数(全称Set fill character设置填充字符)

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout << setw(10) << setfill('*') << a << endl;
    return 0;
}

setw(10)说明设置字段宽度为10,setfill('*')表明当不够时以*****填充剩余部分

2.控制数值格式

fixed:以固定小数点(即定点)表示浮点数,(不会以科学计数法展示了)

scientific:以科学计数法表示浮点数

setprecision:设置浮点数的精度(保留位数),以控制小数点后的数字位数,一般先固定小数点,再设置精度

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	double pi=3.141592653589;
	cout << pi << endl;//原样打印 
	cout << fixed <<pi << endl;//固定点 
	cout << fixed << setprecision(3)<<pi<<endl;//先固定小数点+再设置精度(强制保留3位) 
	cout << scientific << pi << endl;
    return 0;
}

3.控制整数格式

dec:以十进制格式显示整数(默认)

"默认"的含义

设n为整型变量

cpp 复制代码
cout<<dec<<n<<endl;

等价为

cpp 复制代码
cout<<n<<endl;

hex:以十六进制格式显示整数

oct:以八进制格式显示整数

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int n=100;
    cout<<dec<<n<<endl;
    cout<<hex<<n<<endl;
    cout<<oct<<n<<endl;
    return 0;
}

4.控制对齐方式

left:左对齐

right:右对齐(默认)

默认的含义:如果只写setw(),则默认右对齐

cpp 复制代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
	int a=12;
	cout<<setw(5)<<right<<a<<endl;
	cout<<setw(5)<<left<<a<<'x'<<endl;
    return 0;
}
相关推荐
卡提西亚2 分钟前
一本通网站1122题:计算鞍点
c++·笔记·编程题·一本通
im_AMBER8 分钟前
Leetcode 47
数据结构·c++·笔记·学习·算法·leetcode
我命由我1234512 分钟前
Java 并发编程 - Delay(Delayed 概述、Delayed 实现、Delayed 使用、Delay 缓存实现、Delayed 延迟获取数据实现)
java·开发语言·后端·缓存·java-ee·intellij-idea·intellij idea
HLJ洛神千羽12 分钟前
C++程序设计实验(黑龙江大学)
开发语言·c++·软件工程
kyle~17 分钟前
算法数学---差分数组(Difference Array)
java·开发语言·算法
曹牧18 分钟前
C#:三元运算符
开发语言·c#
Jonathan Star36 分钟前
MediaPipe 在Python中实现人体运动识别,最常用且高效的方案是结合**姿态估计**(提取人体关键点)和**动作分类**(识别具体运动)
开发语言·python·分类
滨HI01 小时前
C++ opencv拟合直线
开发语言·c++·opencv
沐浴露z1 小时前
详解JDK21新特性【虚拟线程】
java·开发语言·jvm
艾莉丝努力练剑1 小时前
【C++:红黑树】深入理解红黑树的平衡之道:从原理、变色、旋转到完整实现代码
大数据·开发语言·c++·人工智能·红黑树