OstringStreamでフロートを丸くします
-
04-10-2019 - |
質問
OstringStreamを使用して、FloatからC ++文字列への変換に関する問題があります。これが私の線です:
void doSomething(float t)
{
ostringstream stream;
stream << t;
cout << stream.str();
}
tが値-0.89999の場合、それは-0.9に丸められますが、値が0.0999以下である場合、これよりも1.754E -7が少ない場合、丸めずに印刷するだけです。これの解決策は何ですか。
解決
OstringStreamの精度を使用して設定する必要があります precision
例えば
stream.precision(3);
stream<<fixed; // for fixed point notation
//cout.precision(3); // display only
stream << t;
cout<<stream.str();
他のヒント
特定の数の重要な数字を表示したい場合は、SetPrecision(n)を使用して試してみてください。ここで、Nは必要な数字の数です。
#include <iomanip>
void doSomething(float t)
{
ostringstream stream;
stream << std::setprecision(4) << t;
cout << stream.str();
}
所属していません StackOverflow