2012年02月20日(月) [長年日記]
■ [c++] C++のストリームに小数点以下桁数を指定
以前ストリームに精度を指定する方法をメモしたが、小数点以下の桁数を指定する方法もメモ。std::fixed()を使えばよい。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double d = 12.3456789;
// [1] 精度、floatfield共未指定
cout << "[1] "
<< d
<< endl;
// [2] 精度のみ指定
cout << "[2] "
<< setprecision(5)
<< d
<< endl;
// [3] 精度とfloatfiled指定
// こうすると、精度の意味が小数点以下の桁数になる。
cout << "[3] "
<< fixed
<< setprecision(5)
<< d
<< endl;
// [4] 精度のみ指定(floatfieldの設定は引き継がれる)
cout << "[4] "
<< setprecision(5)
<< d
<< endl;
// [5] floatfieldをリセットして精度を指定
cout << "[5] "
<< resetiosflags(ios_base::floatfield)
<< setprecision(5)
<< d
<< endl;
}
出力結果:
[1] 12.3457 [2] 12.346 [3] 12.34568 [4] 12.34568 [5] 12.346
[ツッコミを入れる]