双精度和oStringStream的奇怪行为

时间:2014-08-20 15:12:27

标签: c++ ostringstream expression-evaluation

所以我正在将表达式求值程序作为工作相关项目的内部组件。但是当谈到浮点数学的输出时,我有一些奇怪的行为......

评估者接受一个字符串

e.evaluate("99989.3 + 2346.4");
//should be 102335.7
//result is 102336

//this function is what returns the result as a string
template <class TYPE> std::string Str( const TYPE & t ) {
    //at this point t is equal to 102335.7
std::ostringstream os;

os << t;
    // at this point os.str() == 102336
return os.str();

看起来好像任何高于e + 004科学记数法的浮点数都被四舍五入到最接近的整数。任何人都可以解释为什么会发生这种情况以及如何克服这个问题。

1 个答案:

答案 0 :(得分:1)

您可以使用 std::setprecision 设置精度。

std::fixed

获得一些帮助
相关问题