1. std::fixed()
#include <iostream>
#include <string>
#include <vector>
int main() {
float a = 4294967244;
float b = 4294967295;
//std::cout << "a=" << a << std::endl;
//std::cout << "b=" << b << std::endl;
std::cout << "a=" << std::fixed << a << std::endl;
std::cout << "b=" << std::fixed << b << std::endl;
}
如果使用注释的内容,那么显示结果为科学计数法,这样看不到具体结果:
如果不用科学计算法来表示一个数,那么在输出的时候就用std::fixed
来看更细的值:
此时,a、b的值都变了,这是float的精度问题。
2. std::setprecision(int n)
如果一个数字太大,无法使用 std::setprecision(int n)
指定的有效数位数来打印,则许多系统会以科学表示法的方式打印。
std::setprecision(int n))
将指定浮点数字的小数点后要显示的位数,而不是要显示的总有效数位数。
std::setprecision(int n))
一般和std::fixed
结合起来用。
下面这句代码是把浮点数a=123.45678999
保留小数点后两位数:
float a=123.45678999;
std::cout<<std::fixed << std::setprecision(2)<<a<<std::endl;
3. std::setw()
std::setw(int n)
是c++中在输出操作中使用的字段宽度设置,设置输出的域宽,n
表示字段宽度。只对紧接着的输出有效,紧接着的输出结束后又变回默认的域宽。
默认为右对齐,并且用空格填充。当后面紧跟着的输出字段长度小于n
的时候,在该字段前面用空格补齐;当输出字段长度大于n
时,全部整体输出。
(1)右对齐,空格填充
std::cout << "TOM" << std::endl;
std::cout << std::setw(6) << "TOM" << std::endl;
从输出图中可以看出,第二行的前面空了三个位置,是因为std::setw(6)
设定了紧跟在后面的"TOM"需要占据六个位置,不够的在前面用空格补齐。
(2)右对齐,其他符号填充
若想使用其他符号填充(例如用“ * ”填充),则可以用:
cout << std::setw(5) << setfill('*') << "0" << "1" << endl;
(3)左对齐
如果想修改成左对齐,则只需要在std::setw(n)
之前加上std::left
即可。
当要输出的字符串宽度大于setw
设置的宽度n
时,直接输出想要输出的字符串即可(此时忽视setw
设置的宽度)。
测试:
#include <iomanip>
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
/*默认为右对齐,此时加不加std::right都可以 */
cout << std::setw(5) << "0" << "1" << endl;
cout << std::setw(5) << "00" << "1" << endl;
cout << std::setw(5) << "000" << "1" << endl;
/*用<<left或者std::left改成左对齐*/
cout << std::left << std::setw(5) << "0" << "1" << endl;
cout << std::left << std::setw(5) << "00" << "1" << endl;
cout << std::left << std::setw(5) << "000" << "1" << endl;
/*当要输出的字符串宽度大于setw设置的宽度时,直接输出想要输出的字符串即可*/
cout << std::right <<std::setw(5) << "0000000" << "1" << endl;
/*用其他符号填充*/
cout << std::right <<std::setw(5) << setfill('*') << "0" << "1" << endl;
cout << std::left << std::setw(5) << setfill('*') << "0" << "1" << endl;
return 0;
}
运行结果: