我必须从字符串中读取FLOT值,精度可达6,当前代码仅读取前6位数字。提前感谢
template <class T>
bool from_string(T& t, const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main()
{
int i;
float f;
// the third parameter of from_string() should be
// one of std::hex, std::dec or std::oct
if(from_string<int>(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
if(from_string<float>(f, std::string("1456.909"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}
发布于 2009-11-04 18:24:46
我很确定它是在读所有的数字。问题似乎出在你所期望的地方。让我们说得更清楚一点:如果在float
中读取1456.90900000000000000000000000000
,您会期望发生什么
发布于 2009-11-05 01:53:56
如果你想做比6位更好的运算,你需要使用双精度,而不是浮点数。你的问题是"6位精度“,也是”前6位数“,但你提供的输入是7位数。
浮点数只能包含6位精度,即x.yzpqrs、xy.zpqrs或xyzpq.rs。如果你想保留6位小数,那么你需要使用double。
例如,您可以使用cout.precision(7)让它输出更多的小数位,在本例中,它将打印正确的答案,即使C实际上并没有存储7位数字,只是近似于正确的答案。
https://stackoverflow.com/questions/1672419
复制相似问题