关于setprecision(n)的问题

来源:互联网 发布:ubuntu 一键openstack 编辑:程序博客网 时间:2024/06/05 04:09

关于setprecision(n)的问题

1

// setprecision example
#include <iostream>
#include <iomanip>
using namespace std;

int main () {
double f =3.14159;
cout << setprecision (5) << f << endl;
cout << setprecision (9) << f << endl;
return 0;
}
输出:


若将以上代码中f设置为double f=0.14159,则结果如下:

结论1setprecision设置浮点数从左起第一个不为零的数位开始计算到右边最后一个不为零的数位为止的有效数位的位数的最大值,并且进行四舍五入。

 

 

2

#include "ostream.h"
#include "istream.h"
#include "iomanip.h"

void main()
{
        double amount=22.0/7;              // 3.142857 142857 14285714
        cout<<amount<<endl;                                //
第一行
        cout<<setprecision(0)<<amount<<endl                 //
第二行
            <<setprecision(1)<<amount<<endl                   //
第三行
            <<setprecision(2)<<amount<<endl;                  //
第四行
}

输出:

分析

第一行的输出数值之前没有设置有效位数,所以用流的有效位数默认设置值6

第二行输出有效位数0C++最小的有效位数为1,所以作为有效位数设置为1来看待;

第三行输出有效位数为1

第四行输出有效位数为2,并四舍五入;

注意:对于第三行,有些人得出的输出如下:

他们给出的根据和理同如下:

   MDSN上的解释:    If the display format is scientific or fixed, then the precision indicates the number of digits after the decimal point. If the format is automatic (neither floating point nor fixed), then the precision indicates the total number of significant digits. This setting remains in effect until the next change. 应该是设置非法参数。

    CC++中当函数的参数非法时,通常默认其参数不起作用!如,
print("%0.2lf/n",je);
这个0就不起作用,其整数部分只是照默认的输出!


:还有的是计算中
好像例如double i=(13/7)                //1.857 142857 142857
cout<<setprecision (5)<<i;
他们的结果是7位小数阿

可是我实践的结果却

还有
但是我输入了一个
double i=1.00000
然后我
cout<<setprecision (5)<<i;
它输出的是 1


真得不懂了
这个为什么呢?

答:尾部所带的所有0都不属于有效数位的范畴。

 

 

原创粉丝点击