C++中的部分Manipulators (控制符)

endl:换行

fixed:用一般的方式输出浮点数(在iostream头文件里)

specify that  (for output sent to the cout stream) decimal format (not scientific notation) be used, and that a decimal point be included (even for floating values with 0 as fractional part)

setprecision:设置精度

setprecision(n) 这里的n当前面有fixed时是小数位数,没有fixed时是有效数字位数

remains in effect until explicitly changed by another call to setprecision
需要 #include <iomanip>

#include  <iomanip> // for setprecision( ) #include  <iostream>
using  namespace  std;
int main (  ) { float   myNumber  =  123.4587 ;
cout  <<  fixed; // use decimal format
cout  <<  “Number is ”  <<  setprecision ( 3 )   <<  myNumber     <<  endl ;
return  0 ;
}

输出123.458

setw:设置域宽(eg:setw(n)),只对紧接着的输出有效。当后面紧跟着的输出字段长度小于n的时候,在该字段前面用空格补齐;当输出字段长度大于n时,全部整体输出。

 

#include  <iomanip> #include  <iostream>
using  namespace  std;
int  main (  ) { float myNumber    = 3.14159; float yourNumber  = 123. 45678 ;
cout  <<  fixed; 
cout  <<  “Numbers are: ”  <<  setprecision ( 3 ) <<  endl <<   setw ( 6 )            <<  myNumber      <<   endl <<   setw ( 6 )            <<  yourNumber   <<   endl ;
return 0 ;
}

输出:

Numbers are:
 3.142
123.457

因为有fixed,所以都是三位小数而非三位有效数字。第一个数不足6位补一个空格,第二个数超六位了,所以输出保留三位小数后的数字。

posted @   脂环  阅读(446)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示
主题色彩