C++保留小数位数

来源:互联网 发布:ge fanuc plc编程软件 编辑:程序博客网 时间:2024/05/01 02:07

注意:

1.只设置setprecision(n)意思是包含小数点前后所有数字的位数。

2.在前一项前添加fixed关键字后可以设置小数点后有效数字的个数。


引用(http://www.cnblogs.com/krisdy/archive/2009/04/17/1438402.html):

“”“

1. C++中格式控制
      在C++中,说到保留小数点后几位有效数字,就会想起setprecision,马上去cplusplus上查了下有关setprecision的资料,看了后明白了,懒得逐字翻译,直接贴在下面了:
Set decimal precision

Sets the decimal precision to be used by output operations.

Behaves as if a call to the stream's member ios_base::precision with n as argument was made.

The decimal precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether thefloatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using thedefault notation, which is neither fixed nor scientific):

  • On the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than theprecision. (此处稍微解释下:在默认情况下,setprecision(n)中的参数n表示的是小数点前后所有的有效数字(从第一个不是0的数字开始计数)位数,并且如果数字本身所有的小数位数比要求保留的位数少的话,不再后面加零凑齐所要求的位数,而在下面所说的fixed和scientific情况下setprecision(n)中的参数n表示的才是小数点后的有效数字位数,并且如果数字本身所有的小数位数比要求保留的位数少的话,在后面加零凑齐,这几点在应用中要注意。)
  • In both the fixed andscientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The number of digits before the decimal point does not matter in this case.

  • This manipulator is declared in header <iomanip>, along with the other parameterized manipulators:resetiosflags,setiosflags, setbase, setfill andsetw. This header file declares the implementation-specificsmanip type, plus any additional operator overload function needed to allow these manipulators to be inserted and extracted to/from streams with their parameters.

”“”