2013-10-18 180 views
5

我无法将字符串转换为双精度。我得到一个字符串,其格式为:33.9425/N 118.4081/W将字符串转换为双精度 - 丢失精度

我第一次调用我的函数trimLastChar(std::string& input)两次,它将删除North,South,East,West字符,然后是正斜杠。此功能正确地返回33.9425118.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缺少...

任何想法如何解决?或者更重要的是,为什么发生这种情况?

+2

...你应该检查你的输出格式,我猜这只是cout上格式化的问题。 – IdeaHat

回答

7

输入时精度不会丢失。它正在输出中丢失。

#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 
$ 
+0

谢谢......那就是诀窍! – Adam

3

您可能有比输出显示更多的数字。默认情况下,只显示少量的数字,您需要使用std::setprecision来查看更多数字。尝试

std::cout << std::setprecision(10) << output << std::endl;