设置浮点数精度(precision、setprecision)

来源:互联网 发布:知乎 入门游戏键盘 编辑:程序博客网 时间:2024/05/01 03:04

在C++中可以人为控制浮点数的精度,也就是说可以用流操纵算子setprecision或成员函数percision控制小数点后面的位数。设置了精度以后,该精度对之后所有的输出操作都有效,直到下一次设置精度为止。无参数的成员函数percision返回当前设置的精度。图11.17中的程序用成员函数precision和流操纵算子setprecision打印出了2的平方根表,输出结果的精度从0连续变化到9。

 // Fig. 11.17: fig11_17.cpp // Controlling precision of floating-point values #include < iostream.h> #include < iomanip.h> #include < math.h> int main()   double root2 = sqrt( 2.0 );   int places;   cout << setiosflags(ios::fixed)       << "Square root of 2 with precisions 0-9.\n"       << "Precision set by the"       << "precision member function:" << endl;   for ( places = 0; places <= 9; places++ ) {     cout.precision( places );     cout << root2 << '\n';     }   cout << "\nPrecision set by the"       << "setprecision manipulator:\n";   for ( places = 0; places <= 9; places++ )     cout << setprecision( places ) << root2 << '\n';   return 0; }

输出结果:

Square root of 2 with pzecisions 0-9.

Precision set by the precision member function:

1

1.4

1.41

1.414

1.4142

1.41421

1.414214

1.4142136

1.41421356

1.414213562

Precision set by the setprecision manipulator:

1

1.4

1.4l

1.414

1.4142

1.41421 ·

1.414214

1.4142136

1.41421356

1.414213562

图11.17 控制浮点数的精度




FROM: http://blog.163.com/kevinlee_2010/blog/static/16982082020141287163589/

0 0