zoukankan      html  css  js  c++  java
  • c/c++输出保留小数

    c语言中,用print可以有格式符号,例如想让a保留两位小数

    float a;
    print( "%.2f", a);

    注意这里如果a是0.1, 那么打印出来会自动补0,也就是结果显示为0.10。

    c++中没有这种格式符,所以用std中函数设定。(iomanip库)

    一种写法是提前声明,一种是cout <<  xxx << endl中声明

    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    int main()
    {
        float a = 0.123;
        cout << a << " without setting" << endl;
    
    
        cout << setprecision(5) <<a << " without fixed" << endl;
    
    
        cout.setf( ios::fixed );
        cout << setprecision(5) << a << " with fixed" << endl;
    
    
        cout.setf(ios::fixed);
        cout.precision(5);
        cout << a << " with fixed" << endl;
    }

    输出结果为  

    0.123 without setting
    0.123 without fixed
    0.12300 with fixed
    0.12300 with fixed

    setprecision()控制输出流,所以要写在cout << xxxxxxxxxxxxx <<endl中,

    cout.precision可以提前控制输出精度,

    两种方法都可以设置精度大小

    fixed是设置补零,如果不想补零,可以关闭fixed设定

    cout.unsetf(ios::fixed);  

    PS:设置精度是会四舍五入的,比如0.987,设置精度为2,则会进一位   输出0.99

    什么时候能够不再这么懒惰
  • 相关阅读:
    C++模板学习之优先队列实现
    static 和const分别怎么用,类里面static和const可以同时修饰成员函数吗?
    C和C++的区别
    C++多态例子_虚函数
    转:master公式(主方法)
    C++11最常用的新特性如下
    转:哈夫曼树详解
    linux shell脚本
    linux 正则表达式
    linux shell命令
  • 原文地址:https://www.cnblogs.com/chaoswr/p/7783515.html
Copyright © 2011-2022 走看看