将字符串转换为双精度-失去精度

亚当

我在将字符串转换为双精度字时遇到麻烦。我得到了一个纬度/经度坐标的字符串,格式为33.9425/N 118.4081/W

我首先调用我的函数trimLastChar(std::string& input)两次,它将删除北,南,东,西字符,然后去掉正斜杠。此函数正确返回,33.9425118.4081以形式正确表示std::string

我正在使用以下代码将我的代码转换std::stringdouble...但是,问题出在,转换损失精度-我怀疑它会四舍五入吗?

// Location In String is what trimLastChar returns
std::stringstream stream(locationInString);
std::cout << "DEBUG: before: " << locationInString << " ";
// output is a double* output = new double passed by reference to my function
stream >> output;
std::cout << output << std::endl;

在这种情况下,输出将产生:

33.9425 
118.408

您会注意到,正确的值应该是,118.4081但缺少1。

任何想法如何解决?或更重要的是,为什么会这样?

瓦克斯拉特

精度不会因输入而损失。它在输出中丢失了。

#include <iostream>
using std::cout;
using std::endl;
int main()
{
  double v = 118.4081;
  cout << v << endl;
  cout.precision(10);
  cout << v << endl;
}

输出:

$ g++ -Wall x.cpp && ./a.out
118.408
118.4081
$

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章