Hey, I am interested to know how I could get numbers to be equal to two significant digits after a point like 1.00, 0.50, 0.33, 0.25, 0.20 0.17 when dividing 1 by x where x is increasing by one in each for loop. The code I wrote is below. The problem is that when I use float, double or long double I get extensions after a dot such as 0.333333 or just one digit after dot like 0.5 or 0.20. So, basically I want two significant digits after a dot for my program.
#include <iostream>
#include <iomanip>
#include <cctype>
#include <string>
usingnamespace std;
//=====================================================================
struct fmt // general format object
{
char form;
int width, precision;
char ch;
fmt( char f, int w, int p = 6, char c = ' ' ) : form( f ), width( w ), precision( p ), ch( c ) {}
};
ostream& operator << ( ostream &strm, fmt o ) // format manipulator
{
char t = tolower( o.form ), c = o.ch;
int w = o.width, p = o.precision;
if ( t == 'i' ) strm << setw( w ); // integer
elseif ( t == 'f' ) strm << fixed << setw( w ) << setprecision( p ); // fixed-point
elseif ( t == 'e' ) strm << scientific << setw( w ) << setprecision( p ); // scientific
elseif ( t == 'a' ) strm << setw( w ); // text
elseif ( t == 's' ) for ( int i = 0; i < w; i++ ) strm << ' '; // space
elseif ( t == 'c' ) for ( int i = 0; i < w; i++ ) strm << c; // character
return strm;
}
//======================================================================
int main()
{
constint w = 8;
#define W << setw( 8 ) <<
#define NL << '\n'
cout W "x" W "x^2" W "x^3" W "1/x" NL << string( 4 * w, '-' ) NL;
for( int n = 1 ; n < 11 ; ++n ) cout W n W n * n W n * n * n << fmt( 'f', w, 2 ) << 1.0 / n NL;
}