Mega Code Archive

 
Categories / C++ Tutorial / Development
 

Controlling precision of floating-point values

#include <iostream> #include <iomanip> #include <math.h> using namespace std; 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; }