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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM