Loading

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 @ 2020-04-23 20:32  脂环  阅读(441)  评论(0编辑  收藏  举报