我在将字符串转换为 double 时遇到问题。我得到一个带有纬度/经度坐标的字符串,格式为 33.9425/N 118.4081/W
我首先调用我的函数 trimLastChar(std::string& input)
两次,这将删除北、南、东、西字符,然后是正斜杠。此函数正确地返回 33.9425
和 118.4081
作为 std::string
。
我正在使用以下代码将我的 std::string
转换为 double
...但是问题是,转换会损失精度——我怀疑是这样变圆了?
// 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
$
关于c++ - 将字符串转换为 double ——失去精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458599/