Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::setprecision

      From cppreference.com
      <cpp‎ |io‎ |manip
       
       
       
      Input/output manipulators
      Floating-point formatting
      Integer formatting
      Boolean formatting
      Field width and fill control
      Other formatting
      Whitespace processing
      Output flushing
      Status flags manipulation
      Time and money I/O
      (C++11)
      (C++11)
      (C++11)
      (C++11)
      Quoted manipulator
      (C++14)
       
      Defined in header<iomanip>
      /*unspecified*/ setprecision(int n);

      When used in an expressionout<< setprecision(n) orin>> setprecision(n), sets theprecision parameter of the streamout orin to exactlyn.

      Contents

      [edit]Parameters

      n - new value for precision

      [edit]Return value

      An object of unspecified type such that

      • ifout is an object of typestd::basic_ostream<CharT, Traits>, the expressionout<< setprecision(n)
      • ifin is an object of typestd::basic_istream<CharT, Traits>, the expressionin>> setprecision(n)

      where the functionf is defined as:

      void f(std::ios_base& str,int n){// set precision    str.precision(n);}

      [edit]Example

      Run this code
      #include <iomanip>#include <iostream>#include <limits>#include <numbers> int main(){constexprlongdouble pi{std::numbers::pi_v<longdouble>}; constauto default_precision{std::cout.precision()};constexprauto max_precision{std::numeric_limits<longdouble>::digits10+1};  std::cout<<"default precision: "<< default_precision<<'\n'<<"maximum precision: "<< max_precision<<"\n\n""precision: pi:\n"; for(int p{0}; p<= max_precision;++p)std::cout<<std::setw(2)<< p<<"  "<< std::setprecision(p)<< pi<<'\n'; std::cout<< std::setprecision(default_precision);// restore defaults}

      Output:

      default precision: 6maximum precision: 19 precision: pi: 0  3 1  3 2  3.1 3  3.14 4  3.142 5  3.1416 6  3.14159 7  3.141593 8  3.1415927 9  3.1415926510  3.14159265411  3.141592653612  3.1415926535913  3.1415926535914  3.141592653589815  3.1415926535897916  3.14159265358979317  3.141592653589793218  3.1415926535897932419  3.141592653589793239

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 183C++98setprecision could only be used with streams
      of typestd::ostream orstd::istream
      usable with any
      character stream

      [edit]See also

      changes formatting used for floating-point I/O
      (function)[edit]
      manages decimal precision of floating point operations
      (public member function ofstd::ios_base)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/io/manip/setprecision&oldid=159185"

      [8]ページ先頭

      ©2009-2025 Movatter.jp