我使用OSTRINGSTREAM从Float转换为C ++字符串有一个问题。这是我的台词:

void doSomething(float t)
{
    ostringstream stream; 
    stream << t;
    cout << stream.str();
}

当t具有-0.89999值时,它的圆形为-0.9,但是当其值为0.0999或少于1.754e -7时,它就不会打印出来。解决方案是什么。

有帮助吗?

解决方案

您需要使用使用的精度 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();
}

如果您想定点而不是科学符号,请使用 std::fixed:

stream << std::fixed << t;

此外,您可能需要设置所述的精度。

采用 SetPrecision:

stream << setprecision(5) <<t ;

现在,您的字符串 stream.str() 将是所需的精度。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top