格式化输出

来源:互联网 发布:rgb2gray python 编辑:程序博客网 时间:2024/05/22 04:34

setprecision一个浮点数指定总得显示位数

#include<iostream>#include<iomanip>int main( int argc, char** argv ){    double num = 123.456789;    //给一个浮点数指定总得显示位数     std::cout << std::setprecision(1) << num << std::endl;    std::cout << std::setprecision(2) << num << std::endl;    std::cout << std::setprecision(3) << num << std::endl;    std::cout << std::setprecision(4) << num << std::endl;    std::cout << std::setprecision(5) << num << std::endl;    std::cout << std::setprecision(6) << num << std::endl;    std::cout << std::setprecision(7) << num << std::endl;    std::cout << std::setprecision(8) << num << std::endl;    std::cout << std::setprecision(9) << num << std::endl;    return 0;}

setw(width)设置域宽

#include<iostream>#include<iomanip>int main( int argc, char** argv ){    //默认右对齐    std::cout << std::setw(8) << "C++" <<  std::setw(6) << 101 << std::endl;     std::cout << std::setw(8) << "Java" << std::setw(6) << 101 << std::endl;    std::cout << std::setw(8) << "HTML" << std::setw(6) << 101 << std::endl;     return 0;} 

left与right操作

#include<iostream>#include<iomanip>int main( int argc, char** argv ){    //right右对齐    std::cout << std::right;    std::cout << std::setw(8) << 1.23 << std::endl;    std::cout << std::setw(8) << 351.34 << std::endl;    //left左对齐     std::cout << std::left;    std::cout << std::setw(8) << 1.23 << std::endl;    std::cout << std::setw(8) << 351.34 << std::endl;       return 0;}

fixed+setpecision修改操作

#include<iostream>#include<iomanip>int main( int argc, char** argv ){    double number = 12345678.9;    //windows系统上,对于很长的浮点数会自动显示科学记数法形式    std::cout << number << std::endl;    //强制数字显示非科学记数法形式,默认修改小数点后六位    std::cout << std::fixed << number << std::endl;    //配合setprecision指定小数点后几位    std::cout << std::fixed << std::setprecision(3) << number << std::endl;     return 0; }

showpoint显示小数点

#include<iostream>#include<iomanip>int main( int argc, char** argv ){    std::cout << 1.23 << std::endl;    std::cout << std::showpoint << 1.23 << std::endl;    std::cout << std::showpoint << 123. << std::endl;}
1 0