• 【C++】浮点数的std::fixed、std::setprecision()、std::setw()用法


    1. 【C++】50.浮点数的std::fixed、std::setprecision()、std::setw()用法
    2. C++中std::setw()的用法

    1. std::fixed()

    #include 
    #include 
    #include 
    
    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 
    #include 
    #include
    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;
    	
    	/*用<
    	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;
    }
    

    运行结果:
    在这里插入图片描述

  • 相关阅读:
    js——继承
    Harbor 安装部署
    Ribbon核心源码剖析
    【Ubuntu20.04安装java-8-openjdk】
    手机没电用日语怎么说?你会吗?柯桥常用日语学习
    A-Level数学例题解析及练习Natural logarithms
    【01】LVGL-CodeBlock模拟器安装 | LVGL工程下载 | PC端模拟LVGL步骤
    Unity 实现原神中的元素反应
    springboot多环境下如何进行动态配置
    实践GoF的设计模式:迭代器模式
  • 原文地址:https://blog.csdn.net/lemonxiaoxiao/article/details/127107121