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

 

posted @   LBNOQYX  阅读(11469)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
· 程序员转型AI:行业分析
点击右上角即可分享
微信分享提示