解析C++浮動小数点のフォーマット出力


C++フォーマット出力浮動小数点数

#include <iostream>
using std::cout;
using std::endl;
using std::fixed;
using std::scientific;
int main()
{
   double x = 0.001234567;
   double y = 1.946e9;
   cout << "Displayed in default format:" << endl << x << '/t' << y << endl;
   cout << "/nDisplayed in scientific format:" << endl << scientific << x << '/t' << y << endl;
   cout << "/nDisplayed in fixed format:" << endl << fixed << x << '/t' << y << endl;
   return 0;
}
Displayed in default format:0.00123457      1.94 e+009 Displayed in scientific format:1.234567 e-003   1.46000 e+009 Displayed in fixed format:0.001235        1946000000000

#include <iostream.h>
main(void)
{
  float a=100100.0, b=0.08;
  cout.setf(ios::right|ios::scientific|ios::showpoint);
  cout.width(20);  
  cout <<(-a*b);

  return 0;
}
-8.0080 e+003

#include <iostream>
#include <iomanip>
#include <limits>
using std::cout;
using std::endl;
using std::setprecision;
using std::numeric_limits;
int main() {
  const double pi = 3.14;
  cout << endl;
  for(double radius = .2 ; radius <= 3.0 ; radius += .2)
    cout << "radius = "
    << setprecision(numeric_limits<double>::digits10 + 1)
    << std::scientific << radius<< "  area = "
         << std::setw(10) << setprecision(6)<< std::fixed << pi * radius * radi
us << endl;
  return 0;
}
radius=2.000001 e-001  ara=   0.256百radius=4.0000 0002 e-001  ara=   0.02400 radius=6.0000 0009 e-001  ara=   1.130400 radius=8.0000 0004 e-001  ara=   2.0960 radius=1.00000 e+000  ara=   3.140000 radius=1.20000000000 e+000  ara=   4.521600 radius=1.39999999999 e+000  ara=   6.1540000 radius=1.9999999999999 e+000  ara=   8.038400 radius=1.799999998 e+000  ara=  10.173600 radius=1.999999999998 e+000  ara=  12.560000 radius=2.9999999999 e+000  ara=  15.197600 radius=2.39999999999 e+000  ara=  18.0850 radius=2.6億001 e+000  ara=  21.226400 radius=2.800000000000 03 e+000  ara=  24.617600

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main( ) {
   ios_base::fmtflags flags = cout.flags( );
   double pi = 3.14285714;
   cout << "pi = " << setprecision(5) << pi << '/n';
   cout.flags(flags);
}
pi=3.1429

#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;
}