C++/Data Type/float output

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Change cout width and precision for string and float number output

  
#include <iostream>
using namespace std; 
int main(void)
{
   cout.precision(4);
   cout.width(10);
   cout << 10.12345 << endl;
   cout.width(10);
   cout.fill("-");
   cout << 10.12345 << endl;
   cout.width(10);
   cout << "Hi!" << endl;
   cout.width(10);
   cout.setf(ios::left);
   cout << 10.12345;
}


Controlling precision of floating-point values

   
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::ios;
using std::setiosflags;
using std::setprecision;
#include <cmath>
int main()
{
   double root2 = sqrt( 2.0 );
   int places;
   cout << setiosflags( ios::fixed) << endl;
   for ( places = 0; places <= 9; places++ ) {
      cout.precision( places );
      cout << root2 << "\n";
   }
   for ( places = 0; places <= 9; places++ )
      cout << setprecision( places ) << root2 << "\n";
   return 0;
}


Floating-point values in system default, scientific, and fixed formats.

   
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
int main()
{
   double x = .001234567, y = 1.946e9;
   cout << "Displayed in default format:\n" << x << "\t" << y << "\n";
   cout.setf( ios::scientific, ios::floatfield );
   cout << "Displayed in scientific format:\n" << x << "\t" << y << "\n";
   cout.unsetf( ios::scientific );
   cout << "Displayed in default format after unsetf:\n" << x << "\t" << y << "\n";
   cout.setf( ios::fixed, ios::floatfield );
   cout << "Displayed in fixed format:\n"<< x << "\t" << y << endl;
   return 0;
}


Output float in default floating-point format

  
#include <iostream>
using namespace std;
int main()
{
  int x = 100;
  double f = 98.6;
  double f2 = 123456.0;
  double f3 = 1234567.0;
  cout << "f, f2, and f3 in default floating-point format:\n";
  cout << "f: " << f << "  f2: " << f2 << "  f3: " << f3 << endl;
  return 0;
}


Output float number with fixed flag

  
#include <iostream>
#include <iomanip>
using namespace std; 
int main(void){
   float value = 0.000123;
   cout << setiosflags(ios::fixed) << value << "\n";
}


Output float type number with scientific format

  
#include <iostream>
#include <iomanip>
using namespace std; 
int main(void){
   float value = 0.000123;
   cout << setiosflags(ios::scientific) << value << "\n";
 }


Set precision for float number

  
#include <iostream>
#include <iomanip>
using namespace std; 
int main(void){
   int i;
   float value = 1.2345;
   for (i = 0; i < 4; i++)
     cout << setprecision(i) << value << "\n";
}