Namespaces
Variants

std:: setprecision

From cppreference.net
< 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)
ヘッダーで定義 <iomanip>
/*unspecified*/ setprecision ( int n ) ;

式内で使用された場合 out << setprecision ( n ) または in >> setprecision ( n ) 、ストリーム out または in precision パラメータを正確に n に設定します。

目次

パラメータ

n - 精度の新しい値

戻り値

未指定の型のオブジェクトであり、以下の条件を満たすもの

  • out が型 std:: basic_ostream < CharT, Traits > のオブジェクトである場合、式 out << setprecision ( n ) は:
    • std:: basic_ostream < CharT, Traits > & を持つ
    • out を持つ
    • f ( out, n ) を呼び出したかのように振る舞う
  • in が型 std:: basic_istream < CharT, Traits > のオブジェクトである場合、式 in >> setprecision ( n ) は:
    • std:: basic_istream < CharT, Traits > & を持つ
    • in を持つ
    • f ( in, n ) を呼び出したかのように振る舞う

関数 f は以下のように定義されます:

void f(std::ios_base& str, int n)
{
    // 精度を設定
    str.precision(n);
}

#include <iomanip>
#include <iostream>
#include <limits>
#include <numbers>
int main()
{
    constexpr long double pi{std::numbers::pi_v<long double>};
    const auto default_precision{std::cout.precision()};
    constexpr auto max_precision{std::numeric_limits<long double>::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
}

出力:

default precision: 6
maximum 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.14159265
10  3.141592654
11  3.1415926536
12  3.14159265359
13  3.14159265359
14  3.1415926535898
15  3.14159265358979
16  3.141592653589793
17  3.1415926535897932
18  3.14159265358979324
19  3.141592653589793239

欠陥報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 183 C++98 setprecision std::ostream または std::istream 型のストリームでのみ使用可能 任意の文字ストリームで使用可能

関連項目

浮動小数点I/Oで使用される書式を変更する
(関数)
浮動小数点演算の10進精度を管理する
( std::ios_base の公開メンバ関数)